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

时间:2021-10-14 06:47:17

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

在角度2的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返回一个模拟英雄的Observable(Observable)。

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

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

3 个解决方案

#1


9  

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

他们使用()的原因是因为它很容易使用它而不是真正的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:

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

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

你的应用程序的其余部分将工作相同,因为()是一个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 complete notification.

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

#2


1  

In the first example, I assume that the HEROES variable 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变量是一个对象数组,其中每个对象对应于接口Hero(或者是Hero类的实例)。当我们在代码中的某个地方调用此函数时,它将如下所示:

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

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

这意味着,当我们使用带有数组的创建方法的Observable作为参数时,在订阅时它会发出整个数组,而不是它的'元素一个接一个

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.

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

Basically, when you create Observable with of method and supply arguments to it, on subscription it emits these arguments one-by-one

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

Here's a good reference

这是一个很好的参考

#3


1  

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()对于在实现异步交互之前维护Observable数据类型很有用(例如,对API的http请求)。

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

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

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
}

#1


9  

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

他们使用()的原因是因为它很容易使用它而不是真正的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:

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

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

你的应用程序的其余部分将工作相同,因为()是一个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 complete notification.

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

#2


1  

In the first example, I assume that the HEROES variable 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变量是一个对象数组,其中每个对象对应于接口Hero(或者是Hero类的实例)。当我们在代码中的某个地方调用此函数时,它将如下所示:

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

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

这意味着,当我们使用带有数组的创建方法的Observable作为参数时,在订阅时它会发出整个数组,而不是它的'元素一个接一个

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.

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

Basically, when you create Observable with of method and supply arguments to it, on subscription it emits these arguments one-by-one

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

Here's a good reference

这是一个很好的参考

#3


1  

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()对于在实现异步交互之前维护Observable数据类型很有用(例如,对API的http请求)。

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

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

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
}