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 ?