beachCode
beachCode

Reputation: 3500

Angular 2 subscribe to an attribute of an observable array

I'm trying to get one attribute from one object in an observable array of objects. I can get everything except isolating the one object and getting the individual properties.

Here's the service method that's successfully getting the array:

getItems(): Observable<IItem[]> {
    return this.get(this.baseUrl + '/items')
      .map((res: Response) => <IItem[]>res.json())
      .do(data => console.log("Items: " + JSON.stringify(data)))
      .catch(this.handleError);
  }

Trying to get just one object isn't working:

 getItem(name: String): Observable<IItem> {
    return this.getItems()
      .map((items: IItem[]) => items.find(item => item.name === name))
      .do(item => console.log("Item: " + item)) 
      .catch(this.handleError);
  }

Component

this._itemsApi.getItem("test")
      .subscribe(
        item => this.testItem = item,
        error => this.errorMessage = <any>error);

Template

 <widget icon="file" [count]="testItem?.value">

JSON

["name: test, value: 1","name: test2, value: 0"]

Upvotes: 1

Views: 1458

Answers (2)

isuruAb
isuruAb

Reputation: 2240

Try this. LinQ for TypeScript. this will help you to find one from the array of objects. https://github.com/kutyel/linq.ts

Follow it's documentation it has everything you need to do.

Upvotes: 2

Sumit Dhameja
Sumit Dhameja

Reputation: 141

You have an array of strings, and not array of Objects. Reformat you API to return back array of objects -> [{"key": "value1"},{"key": "value2"}]. Then you can iterate over these objects and use item.value to get the value of a given item.

Upvotes: 1

Related Questions