问题
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'])));
}
Now we know that this.route.params returns an observable, while
this.heroService.getHero(+params['id']) returns a promise
Here is the signature for 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.
Are they compatible with each other?
Furthermore the console
console.log(this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id'])));
outputs
AnonymousSubject {_isScalar: false, observers: Array[0], closed: false, isStopped: false, hasError: false…}
shouldnt the _isScalar be set to true, since the function outputs a promise?
回答1:
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>;
The switchMap implementation will see that the promise is converted to an observable.
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.
来源:https://stackoverflow.com/questions/41916444/is-observable-and-promise-compatible-in-rxjs