Reputation: 1011
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?
Upvotes: 0
Views: 75
Reputation: 2113
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).
Upvotes: 1