为什么我们应该使用()函数的RxJs? [英] Why we should use RxJs of() function?

查看:149
本文介绍了为什么我们应该使用()函数的RxJs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular2的angular.io教程的服务部分我点击了一个名为of.for的方法,例如:

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

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

或以下样本:

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刚解释

in angular.io Just explained


使用()的RxJS返回模拟英雄的Observable
(可观察)。

used RxJS of() to return an Observable of mock heroes (Observable).

并没有解释为什么我们应该使用函数以及它究竟做了什么以及它有什么好处?

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

推荐答案

他们使用 of()的原因是因为它很容易使用它而不是真正的HTTP调用。

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

在实际的应用程序中,您可以实现 getHeroes(),例如:

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

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

但是因为你只想使用模拟响应而不创建任何真正的后端你可以使用 of()来返回虚假回复:

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);
}

您的应用程序的其余部分将起作用,因为 of()是一个Observable,您可以稍后订阅或链接运算符,就像您使用 this.http.get(...)

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(...).

()唯一的作用就是它立即将其参数作为单一排放量发出订阅后,然后发送完整的通知。

这篇关于为什么我们应该使用()函数的RxJs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆