【问题标题】:What is the difference between using 'from' and 'of' when using switchMap?使用switchMap时使用'from'和'of'有什么区别?
【发布时间】:2019-06-05 00:50:52
【问题描述】:

这是我使用 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 函数的理解是,它会返回包装在 observable 中的 '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 运算符不返回一个 observable 呢?

编辑:这不是RxJs Observable of vs from 的重复,因为我不是在询问fromof 的输入参数。我的问题是fromof 都应该是可观察的,是吗?但是当我使用from 时,switchMap 抱怨它没有接收到 observable 并且它只是从数组中获取“1”。希望这可以澄清。

【问题讨论】:

标签: typescript rxjs


【解决方案1】:

不是从 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)

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 2018-05-14
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    相关资源
    最近更新 更多