Are*_*ani 23 javascript service rxjs angular2-services angular
在角度为2的angular.io教程的服务部分,我点击了一个名为of.for的方法,例如:
getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
Run Code Online (Sandbox Code Playgroud)
或在下面的样本:
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));
}
Run Code Online (Sandbox Code Playgroud)
在angular.io刚刚解释
使用()的RxJS返回一个模拟英雄的Observable(Observable).
并没有解释为什么我们应该使用功能,它究竟做了什么,它有什么好处?
mar*_*tin 36
他们使用的原因of()是因为它很容易使用它而不是真正的HTTP调用.
在实际的应用程序中,您可以getHeroes()像这样实现:
getHeroes(): Observable<Hero[]> {
return this.http.get(`/heroes`);
}
Run Code Online (Sandbox Code Playgroud)
但是,由于您只想使用模拟响应而不创建任何真正的后端,您可以使用of()返回虚假响应:
const HEROES = [{...}, {...}];
getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
Run Code Online (Sandbox Code Playgroud)
您的应用程序的其余部分将工作相同,因为它of()是一个Observable,您可以稍后订阅或链接运算符,就像您使用它一样this.http.get(...).
唯一of()能做的就是它在订阅时立即将其参数作为单个排放发出,然后发送complete通知.
Observable.of()对于在实现异步交互之前维护Observable数据类型很有用(例如,对API的http请求).
正如Brandon Miller建议的那样,Observable.of()返回一个Observable,它立即发出作为参数提供给()的任何值,然后完成.
这比返回静态值更好,因为它允许您编写可以处理Observable类型(同步和异步工作)的订阅者,甚至在实现异步过程之前.
//this function works synchronously AND asynchronously
getHeroes(): Observable<Hero[]> {
return Observable.of(HEROES)
//-OR-
return this.http.get('my.api.com/heroes')
.map(res => res.json());
}
//it can be subscribed to in both cases
getHeroes().subscribe(heroes => {
console.log(heroes); // '[hero1,hero2,hero3...]'
}
//DON'T DO THIS
getHeroesBad(): Array<Hero> {
return HEROES //Works synchronously
//-OR-
return this.http.get('my.api.com/heroes') //TypeError, requires refactor
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12594 次 |
| 最近记录: |