1
votes

I have some questions about Angular Service Tutorial Code:

  1. What does the TODO comment mean in the below code?
  2. If we add a message here, is it possible that the message is added before the HEROES are fetched because Observable is asynchronous and we do not have control over it?
  3. Would it be better to add the message in the subscribe function of the caller who receives the Observable?
getHeroes(): Observable<Hero[]> {
    // TODO: send the message _after_ fetching the heroes
    this.messageService.add('HeroService: fetched heroes');
    return of(HEROES);
  }

I expect the "HEROES are fetched" message is only added after the HEROES are actually fetched.

1
yes it would be better if you add this in subscribe of callerPalak Jadav

1 Answers

0
votes

you have some options depending on what you want... one is to put it in the subscribe, but this can result in code duplication, as everywhere you subscribe to getHeroes() you'll need to remember to add the messageService line and potentially modify it if it ever changes, which isn't ideal from a code maintenance perspective if you really want this to happen everytime getHeroes() is called... instead you could do this:

getHeroes(): Observable<Hero[]> {
  return of(HEROES).pipe(tap(() => this.messageService.add('HeroService: fetched heroes')));
}

now using the tap operator, you've put this messageService action as part of the stream, but after the heroes are successfully fetched. Alternatively, this set up may work as well:

getHeroes(): Observable<Hero[]> {
  return defer(() => {  
    this.messageService.add('HeroService: fetching heroes');
    return of(HEROES);
  });
}

this set up instead puts the messageService action before actually fetching the heroes, but putting the action in the stream with defer guarantees the action won't occur until the subscription is actually triggered instead of just when the stream is built.