How to modify data in Observable in Angular 2?

You can do the processing in your GetData's code, within the 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 receive the object in your subscribe, the items should have the IDs assigned.

Here's the reference to the RxJs Observable's documentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-map


the idea is to :

  • get the result
  • map the result to get the json only
  • as your json is an array, produce an Observable for each data, then change its id and sent the data back
  • gather them back in an array

the mergeMap (replaced flatMap in rxjs 5.5+) operator is used because an Observable operator always sends back an Observable, but since we create an Observable inside the result itself, it produces an Observable>, mergeMap removes an Observable layer. Hope this 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()
   );
}