在rxjs中是否可观察并承诺兼容? [英] Is observable and promise compatible in rxjs?
问题描述
在官方的 angular2教程中,其中包含以下内容代码
In the official angular2 tutorial it contains the following code
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
.subscribe(hero => this.hero = hero);
console.log(this.route.params);
console.log(this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id'])));
}
现在我们知道 this.route.params
返回一个可观察到的内容,而 this.heroService.getHero(+ params ['id'])
返回承诺
Now we know that this.route.params
returns an observable, while
this.heroService.getHero(+params['id'])
returns a promise
这是 rxjs
switchmap
switchMap(project: function: Observable, resultSelector: function(outerValue, innerValue, outerIndex, innerIndex): any): Observable
我们看到第一个参数具有一个发出可观察值的函数.
We see that the first parameter takes a function that emits an observable.
但是在上面的示例中,我们实际上传递了一个发出承诺的函数.
However in the example above we actually passed in a function that emits a promise.
它们彼此兼容吗?
此外,控制台
console.log(this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id'])));
输出
AnonymousSubject {_isScalar: false, observers: Array[0], closed: false, isStopped: false, hasError: false…}
_isScalar
是否应该设置为true,因为该函数会输出一个Promise?
shouldnt the _isScalar
be set to true, since the function outputs a promise?
推荐答案
在许多地方,RxJS API接受 ObservableInput
:
In many places, the RxJS API accepts an ObservableInput
:
export type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T>;
可以是可观察的,应许的或类似于数组的可迭代对象.
Which can be an observable, a promise or an array-like, iterable object.
In the code you have included in your question, the project
function passed to switchMap
returns a promise. That's fine, as switchMap
accepts project
functions that return an ObservableInput
:
export function switchMap<T, R>(
this: Observable<T>,
project: (value: T, index: number) => ObservableInput<R>
): Observable<R>;
switchMap
实现将看到将诺言转换为可观察的.
The switchMap
implementation will see that the promise is converted to an observable.
关于所得的可观察对象的内部 _isScalar
属性,当promise解析并将解析的值存储在内部时,它将设置为 true
.可观察的.我的理解是,在RxJS中, scalar 不是指将要发射的值的数量,而是指所说的值是否可用于立即发射.
Regarding the resultant observable's internal _isScalar
property, it will be set to true
when the promise resolves and the resolved value is stored within the observable. My understanding is that in RxJS, scalar does not refer the the number of values that will be emitted, but instead refers to whether or not said values are available for immediate emission.
这篇关于在rxjs中是否可观察并承诺兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!