Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

in service section of angular.io tutorial for angular2 I hit a method named of.for example :

getHeroes(): Observable<Hero[]> {
  return of(HEROES);
}

or in below sample:

getHero(id: number): Observable<Hero> {
  // Todo: send the message _after_ fetching the hero
  this.messageService.add(`HeroService: fetched hero id=${id}`);
  return of(HEROES.find(hero => hero.id === id));
}

in angular.io Just explained

used RxJS of() to return an Observable of mock heroes (Observable<Hero[]>).

and It was not explained why we should use of operator and exactly what does it do and what are its benefits?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
107 views
Welcome To Ask or Share your Answers For Others

1 Answer

The reason why they're using of() is because it's very easy to use it instead of a real HTTP call.

In a real application you would implement getHeroes() like this for example:

getHeroes(): Observable<Hero[]> {
  return this.http.get(`/heroes`);
}

But since you just want to use a mocked response without creating any real backend you can use of() to return a fake response:

const HEROES = [{...}, {...}];

getHeroes(): Observable<Hero[]> {
  return of(HEROES);
}

The rest of your application is going to work the same because of() is an Observable and you can later subscribe or chain operators to it just like you were using this.http.get(...).

The only thing that of() does is that it emits its parameters as single emissions immediately on subscription and then sends the complete notification.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...