Question:
Update Observable with value from a different Observable in Angular

Problem

I am having trouble to figure out how I can update the result of one Observable with the result of another:


this._http.get<JSON>(url, { params })

.pipe(map((res: JSON) => this.getObjectFromJson(res)))

.subscribe(myObject => {

    this.getValueToUpdate(myObject).subscribe(newValue => {

        myObject.some.value = newValue;

    });

});

// return Observable<myObect>;


What is the proper sequence of rxjs operators to achieve this without these subscribes and being able to return the resulting Observable to be used later?


Solution

You are looking for switchMap:


this._http.get<JSON>(url, { params }).pipe(

  map((res: JSON) => this.getObjectFromJson(res)),

  switchMap(myObject => {

    return this.getValueToUpdate(myObject).pipe(

      // probably here you need also a catchError(err => ...),

      map(newValue => {

        myObject.some.value = newValue;

        return myObject;

      })

    );

  })

).subscribe(myObject => {

  // here myObject is updated with newValue

});


It allows to invoke another async operation and switch (i.e. observe) on that.

The inner pipe, using the map operator, allows to combine the result of the nested async operation with the previous result.


Suggested blogs:

>How to make the dropdown for this button ADA accessible in Angular?

>How to update properties value with event in template Angular?

>Unit Test Angular Standalone Component, Overriding Provider not used

>How to Import componet's own module using Angular?

>Why component does not display variable of another component in Angular?

>What are the ways to pass parameters to Angular service?

>How to access variables in a function using Angular?

>How can I close a bootstrap modal using Angular?

>Fix: Strange compilation error with Typescript and Angular

>Uploading files and JSON data in the same request with Angular

>CRUD Operations In ASP.NET Core Using Entity Framework Core Code First with Angularjs

>CRUD Operation on Angular

>What is pipe in Angular?

>A Complete Guide To Angular Routing


Ritu Singh

Ritu Singh

Submit
0 Answers