Is observable and promise compatibility in rxjs?

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 what the this.route.paramsobservable returns, while the   this.heroService.getHero(+params['id'])promise returns

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 above example, we actually passed in a function that emits a promise.

Are they compatible with each other?

In addition, the console

console.log(this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id'])));

exits

AnonymousSubject {_isScalar: false, observers: Array[0], closed: false, isStopped: false, hasError: false…}

should not be set _isScalarto true, since the function displays a promise?

+4
source share
1 answer

API- RxJS ObservableInput:

export type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T>;

, , .

, , project, switchMap, . , switchMap project , ObservableInput:

export function switchMap<T, R>(
  this: Observable<T>,
  project: (value: T, index: number) => ObservableInput<R>
): Observable<R>;

switchMap , .

_isScalar, true, , . , RxJS , , , .

+5

Source: https://habr.com/ru/post/1668153/


All Articles