使用switchMap时,使用“ from”和“ of”有什么区别?

时间:2019-06-04 10:25:13

标签: typescript rxjs

这是我使用RxJS的TS代码:

function getParam(val:any):Observable<any> {
        return from(val).pipe(delay(1000))
    }

    of(1,2,3,4).pipe(
        switchMap(val => getParam(val))
    ).subscribe(val => console.log(val));

我对getParam函数的理解是,它将返回包裹在可观察值中的“ val”。但是,switchMap会引发以下错误:

hostReportError.js:5 Uncaught TypeError: You provided '1' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:39)
    at Module.from (from.js:15)
    at getParam (index.ts:6)
    at SwitchMapSubscriber.eval [as project] (index.ts:8)
    at SwitchMapSubscriber._next (switchMap.js:43)
    at SwitchMapSubscriber.Subscriber.next (Subscriber.js:63)
    at Observable.eval [as _subscribe] (subscribeToArray.js:7)
    at Observable._trySubscribe (Observable.js:50)
    at Observable.subscribe (Observable.js:36)
    at SwitchMapOperator.call (switchMap.js:27)

如果我将getParam的代码更改为:

function getParam(val:any):Observable<any> {
    return of(val).pipe(delay(1000))
}

它按预期返回4。那么为什么from运算符在这种情况下不返回可观察值呢?

编辑:这不是RxJs Observable of vs from的副本,因为我没有询问fromof的输入参数。我的问题是fromof都应该是可观察的,是吗?但是,当我使用from时,switchMap抱怨它没有收到可观察到的东西,而只是从数组中得到'1'。希望这可以澄清。

1 个答案:

答案 0 :(得分:2)

不是从switchMap抛出的错误
getParam(val:any)有一个数字,所以from()不能接受它作为输入, 但是of()可以


    hostReportError.js:5 Uncaught TypeError: 
      You provided '1' where a stream was expected. 
      You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:39)
    at Module.from (from.js:15)