问题
Taking example of HeroService from angular documentation.
Below is a POST method in HeroService
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
We can see that every time addHero is called a new Observable is returned.
Ok now here is the service call from HeroComponent
this.heroesService
.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
Now In my component this add hero service call is happening very frequently one after another. Each addHero call is returning a new Object of Observable and it is being subscribed.
My question is what is the correct way of subscribing to this service in my use case where addHero is frequently being called one after another 1000 of times.
I should be calling the hero service like this
addHero(){
this.heroesService
.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
}
Or I should call the hero service like this, so that only one observable object is created for each call
const req = this.heroesService.addHero(newHero);
addHero(){
req.subscribe(hero => this.heroes.push(hero));
}
What is the difference between both approaches apart from that only one object of Observable is created in second approach. Also what are the disadvantages or advantages of both the approaches.
For my scenario which is the correct implementation ? Does the second approach makes any difference ? What will happen in terms of memory leak if I go with the first approach ?
回答1:
HttpClient calls complete internally after a request has completed so you wouldn't have to deal with memory leaks and manual unsubscibing.
Both of your examples do the same thing but the first one is more readable.
回答2:
This one is preferred because after execution observable will be completed and you can't reuse it.
addHero(){
this.heroesService
.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
}
In case you need call your service 1000 time in short time maybe it will be better call dedicated service for bulk read.
About memory leaks.
It is safe because this.http.post will return Observable which complete with any first result for success and for error.
Unsubscribing is a MUST
Also you should unsubscribe, you can read about it here
来源:https://stackoverflow.com/questions/61353881/how-to-correctly-subscribe-angular-httpclient-observable