在 Angular 的service类里,导入Observable和of:
of(HEROES) returns an Observable that emits a single value, the array of mock heroes.
下面是消费端如何调用这个返回Observable的TypeScript代码:
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
注意将其同之前的同步API相比较:
The new version waits for the Observable to emit the array of heroes—which could happen now or several minutes from now. The subscribe() method passes the emitted array to the callback, which sets the component’s heroes property.
第32行,调用OBservable API的subscribe方法,方法接收一个回调函数,设置Component的heroes属性为Observable里包裹的数组。
在调试器里能观察到这个回调函数是如何被observable框架异步调用的: