arcee123 arcee123 - 1 year ago 100
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

, in which has multiple JSON entries:


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

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


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:


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

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

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


The function
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 Source

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

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

See demo plunker here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download