gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:52:24 24 4
gpt4 key购买 nike

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

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

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

并且没有解释为什么我们应该使用 of 运算符,它到底做了什么,它有什么好处?

最佳答案

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

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

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

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

const HEROES = [{...}, {...}];

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

您的应用程序的其余部分将以相同的方式工作,因为 of() 是一个 Observable,您稍后可以像使用 this.http 一样订阅或链接操作符。获取(...)

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

关于javascript - 为什么我们应该使用 RxJs of() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com