Dhruvan Ganesh Dhruvan Ganesh - 23 days ago 9
TypeScript Question

Reusing code in Angular 2, RxJS -- repetitive code within Subscriber body

Problem

I'm using a couple of

vars in Angular2 to get data from a service and update an Array in the controller.

The problem is all the respective
.subscribe()
functions carry out the same operations and I cannot find a way to reuse the code -- maybe passing a lambda function into the body of the
.subscribe()
?

It doesn't make sense to retype the same code again and again -- it impacts the readability of the component.

Scenario:

Updating a chart with data from different sources

this.catagoryASubject.subscribe(
value => {
// updating array and chart
this.radarChartData.forEach((val, i) => { if (val.label == value.name) { this.radarChartData[i].data = value.data } });
},
err => console.log("error"),
() => console.log("complete")
);

this.catagoryBSubject.subscribe(
// same code as in the above subscriber
);

Answer

You can use let() operator to group common functionality of observable chains. It takes observable as input and returns an observable, so you could write:

function updateChart(observable: Observable<any>) {
  return observable
    .map(value => {/* do your thing*/})
 // .filter().switchMap().do() // whatever
    .catch(error => console.log("error"))
}

and then use it:

this.catagoryASubject.let(updateChart).subscribe();
this.catagoryBSubject.let(updateChart).subscribe();
this.catagoryCSubject.let(updateChart).subscribe();

I prefer to use subscribe() just as a trigger, and not do any processing work there. It's much cleaner, and you can easily switch to async pipe when you need to...

this.A = this.catagoryASubject.let(updateChart);

<div> {{ A |async |json }} </div>