arcee123 arcee123 - 4 months ago 26
Javascript Question

How to filter Promise during angular2 service call

I am trying to develop a mockup on Angular 2. In this case, I have a model called

Layer
, in which has multiple JSON entries:

Layer.ts



export class Layer {
model: number;
layer: string;
loaded: number;
}


I also have a mock-layer injector for the mockup:

mock-layer.ts



import { Layer } from './layer';

export const LAYERS: Layer[] = [
{model: 9.1, layer: 'SIF', loaded: 1},
{model: 9.1, layer: 'AW', loaded: 1},
{model: 9.1, layer: 'DW', loaded: 1},
{model: 8.7, layer: 'SIF', loaded: 1},
{model: 8.7, layer: 'AW', loaded: 1},
{model: 8.7, layer: 'DW', loaded: 1}
];


In the real world, I would only return 1 model '9.1' or '8.7'. However, I am in mock-up phase, and I'm pulling my two examples right now.

To service this data, I have a layer service:

layer.service.ts



import { Injectable } from '@angular/core';

import { LAYERS } from './mock-layers';

@Injectable()
export class LayerService {
getLayers() {
return Promise.resolve(LAYERS);
}

}


The function
getLayers()
returns all of the layer records.
For the example I am making, how do I return only those layers that fit a certain variable (e.g.
Model = '9.1'
)?

Answer

You can use Array#filter() before creating the Promise:

getLayers() {
  return Promise.resolve(LAYERS.filter(layer => layer.model === 9.1));
}

See demo plunker here.