I have an existing function which does some amount of work calling HTTP endpoints that takes care of managing some logic in my Angular component. A requirement comes in so that in a certain instance we need to all of the existing logic to be called, but also another HTTP call to be made. Below is an annotated version of my attempt.
public resolveComponent(action: string) { //if called with no parameters, don't do anything //otherwise, call one of the two endpoints. let preAction = (x: any) => { if (action === "replay") { return this.remediationService .replayRemediation(this.workflow.Id); } else if (action === "remove") { return this.remediationService .removeRemediation(this.workflow.Id); } else { return of([]); } } this.remediationService .resolveComponent(component) .pipe( //the line below was what I added after new requirement mergeMap(preAction), mergeMap(x => { //grabs updated data from server return this.remediationService.remediationComponent(component.Id); }) ) .subscribe((x: SomeModel) => { //logic happens }); }
This performs the work as expected, but is this the best way to go about conditionally chaining observables?
A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output. Subscribing to the output Observable will also subscribe to the input Observable.
Using pipe to combine operators The order of the operators is important because when a user subscribes to an observable, the pipe executes the operators in a sequence in which they are added. To use observable we need it to import from the rxjs library.
pipe() can be called on one or more functions, each of which can take one argument ("UnaryFunction") and uses it to return a value. It returns a function that takes one argument, passes it to the first UnaryFunction, and then passes the result to the next one, passes that result to the next one, and so on.
Use iif
rxjs.
iif
accepts a condition function and two Observables. When
https://www.learnrxjs.io/operators/conditional/iif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With