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

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

问题描述

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

在 angular.io 中刚刚解释过

in angular.io Just explained

使用 RxJS of() 返回一个模拟英雄的 Observable(可观察到的).

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

并且没有解释为什么我们应该使用 of 运算符以及它的作用和好处是什么?

and It was not explained why we should use of operator 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(...).

of() 唯一能做的就是在订阅时立即将其参数作为单个发射发出,然后发送 complete 通知.

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

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

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