Home > Mobile >  This pattern seems wrong in angular. Multiple calls to an api is generating multiple subscriptions
This pattern seems wrong in angular. Multiple calls to an api is generating multiple subscriptions

Time:01-28

In my Angular 2 app I have the following:

  ngOnInit() {
    debugger;
    this.activatedRoute.paramMap.subscribe((params) => {
      this.rowid = params.get('rowid')
      
      this.apiService.getrow(this.rowid).subscribe((data) => {
        this.data = data;
        //Validations
        if (this.data == null) return;
        if (!("oid" in data)) return;
        let oid:string =data["oid"]
      })
    })
  }
}

This seems wrong because every time the params change we create a new api service call that create a new subscription. I rather not use activatedRoute snapshot.
Is there a better pattern for this. Is there a better way to do this?

CodePudding user response:

You can go with a pipe:

import { take } from 'rxjs/operators';

this.apiService.getrow(this.rowid).pipe(take(1)).subscribe(...)

and it will take a value from sub and unsubscribe.

If you don't want to watch for url params changes, you can consider using BehaviorSubjects. Thus, you can create a service that gets and sets the rowid value as a BehaviorSubject, and then subscribe to it instead of the router. Inside that subscription, you can subscribe to api service (and you can also use take1 there).

  •  Tags:  
  • Related