Dhruvan Ganesh Dhruvan Ganesh - 1 year ago 95
TypeScript Question

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


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
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

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


Updating a chart with data from different sources

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")

// same code as in the above subscriber

Answer Source

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:


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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download