How do I change data in an Observable in Angular 2?

I am working on learning Angular 2 and Typescript. I am creating a simple web application that grabs data from the WEB API and displays it in a list. Then, as soon as the user clicks on an item in the list, they are taken to the details page.

I have a service that I created to call an API that does the following:

   GetData() { 
         let data = this.http.get('http://server.name/api/GetData')
                  .map((res) => res.json());
         return data; 
   }

      

Then, in the component, I subscribe to data like this:

      this.myService.GetData()
      .subscribe((myService) => this.items = myService);

      

When http.get returns, I would like to do some processing on the JSON objects before I return from the GetData () method. For example, add a new property named ID. Essentially something like the pseudo code below:

 for each(item in data) { 
     item.ID = newID(); //method for creating IDs 
 }

      

  • Is this something you can do?
  • If so, is this what SHOULD be done, or is there a better way to accomplish what I am trying to do?

thank

+3


source to share


2 answers


You can do the processing in your GetData code by map

:

// For RxJS v5 
    this.http
      .get('http://server.name/api/GetData')
      .map(result => {
         const items = <any[]>result.json(); // could be SomeItem[] instead of any[]
         items.forEach(item => item.ID = ...);
         return items;
      });

// For RxJS v6 
    this.http
     .get('http://server.name/api/GetData')
     .pipe(map(result => {
        const items = <any[]>result.json(); // could be SomeItem[] instead of any[]
        items.forEach(item => item.ID = ...);
        return items;
      }));

      



Then, when you get an object in your subscription, the items must have IDs assigned.

Here is a link to the RxJs Observable documentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-map

+5


source


the idea is as follows:

  • get the result
  • display the result to get only json
  • since your json is an array, create an Observable for each of the data, then change its id and send the data back
  • collect them back into an array


the mergeMap operator is used (replaced by flatMap in rxjs 5.5+) because the Observable operator always sends back an Observable, but since we create an Observable inside the result itself, it creates an Observable> mergeMap removes the Observable layer. Hope it helps

GetData():Observable<WhateverWithIDInside[]> { 
  let data = this.http.get('http://server.name/api/GetData')
    .map(res => res.json())
    .mergeMap(dataArr =>
      Observable.from(dataArr)
        .map(data => {
          data.ID = newID();
          return data;
        })
        .toArray()
   );
}

      

+1


source







All Articles