javascript 为什么我们应该使用 RxJs of() 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47889210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:40:40  来源:igfitidea点击:

Why we should use RxJs of() function?

javascriptangularservicerxjsangular2-services

提问by Aref Zamani

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

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

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

在 angular.io 中刚刚解释过

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

使用 RxJS of() 返回一个模拟英雄的 Observable (Observable)。

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

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

回答by martin

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

他们之所以使用of()它,是因为它非常容易使用,而不是真正的 HTTP 调用。

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

在实际应用程序中,您将getHeroes()像这样实现,例如:

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:

但是由于您只想使用模拟响应而不创建任何真正的后端,因此您可以使用它of()来返回假响应:

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

您的应用程序的其余部分将继续工作,因为它of()是一个 Observable,您可以像使用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 completenotification.

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

回答by zhark

Observable.of() is useful for maintaining the Observable data type before implementing an asynchronous interaction (for example, an http request to an API).

Observable.of() 可用于在实现异步交互(例如,对 API 的 http 请求)之前维护 Observable 数据类型。

As Brandon Millersuggests, Observable.of() returns an Observable which immediately emits whatever values are supplied to of() as parameters, then completes.

正如Brandon Miller 所建议的,Observable.of() 返回一个 Observable,它立即发出作为参数提供给 of() 的任何值,然后完成。

This is better than returning static values, as it allows you to write subscribers that can handle the Observable type (which works both synchronously and asynchronously), even before implementing your async process.

这比返回静态值要好,因为它允许您编写可以处理 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
}

回答by vanelizarov

In the first example, I assume that the HEROESvariable is an array of objects, in which every object corresponds to interface Hero(or is the instance of class Hero). When we call this function somewhere in the code, it will act like this:

在第一个例子中,我假设HEROES变量是一个对象数组,其中每个对象都对应于 interface Hero(或者是 class 的实例Hero)。当我们在代码的某处调用这个函数时,它会像这样:

heroService.getHeroes()
  .subscribe((heroes: Hero[]) => {
    console.log(heroes) 
    // will output array of heroes: [{...}, {...}, ...]
  })

It means, that when we use Observable's ofcreation method with array as argument, on subscription it will emit the whole array, not its' elements one-by-one

这意味着,当我们使用数组作为参数Observableof创建方法时,订阅时它将发出整个数组,而不是一个一个的元素

In the second example, when we subscribe to Observable, that was returned from getHero()method, it emits only one hero, whose id corresponds to given id.

在第二个示例中,当我们订阅ObservablegetHero()方法返回的 时,它只发出一个英雄,其 id 对应于给定的 id。

Basically, when you create Observablewith ofmethod and supply arguments to it, on subscription it emits these arguments one-by-one

基本上,当您Observable使用of方法创建并为其提供参数时,在订阅时它会一一发出这些参数

Here's a good reference

这是一个很好的参考