1

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')?

Community
  • 1
  • 1
arcee123
  • 101
  • 9
  • 41
  • 118

1 Answers1

1

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

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

See demo plunker here.


Update: per coments, Why === and not =?

= is attribution, so:

LAYERS.filter(layer => layer.model = 9.1)

Is just plain wrong in this case. It is not filtering anything, it is (try it out in the plunker) basically overwriting every layer.model to 9.1.

===, on the other hand, is the strict equality operator:

LAYERS.filter(layer => layer.model === 9.1)

The code above will result in a array where the contents are every LAYERS element that have the model property strictly equal to 9.1.

To understand more the "strictly" part, check this link.

Community
  • 1
  • 1
acdcjunior
  • 132,397
  • 37
  • 331
  • 304