【问题标题】:mergeMap does not exist on type observable可观察类型上不存在mergeMap
【发布时间】:2018-10-12 18:33:53
【问题描述】:

我正在尝试在rxjs6 中使用mergeMap,但出现此错误:

Property 'mergeMap' does not exist on type 'Observable<{}>'

我尝试了import 'rxjs/add/operator/mergeMap';,但它不起作用。

我做错了什么?


import {from, Observable} from 'rxjs';

export class Test {

    public doSomething(): Observable<any> {
        return from(...).mergeMap();
    }

}

【问题讨论】:

    标签: typescript rxjs reactivex rxjs6


    【解决方案1】:

    没错,自 RxJS 6 以来,运算符的“补丁”样式已被删除。您最好更新代码以仅使用“可管道”运算符或安装提供与 RxJS 5 向后兼容的 rxjs-compat 包。

    更详细的描述见官方文档:https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md

    ...更具体地说,这部分:https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#backwards-compatibility

    【讨论】:

    • 谢谢@martin。我使用提供的信息解决了pipe 运算符的问题。也发布了我的解决方案。
    • 文档链接不再起作用。让我们尝试更新您的参考资料@martin
    【解决方案2】:

    组件 Html 是这样的

    <input type="text" placeholder="input first" id="input1">
    <input type="text" id="input2" placeholder="input second">
    <span></span>
    

    导入所需函数

    import { fromEvent } from 'rxjs'
    import { map, mergeMap } from 'rxjs/operators'
    
    
    var span = document.querySelector('span');
    var input1 = document.querySelector('#input1');
    var input2 = document.querySelector('#input2');
    
    var obs1 = fromEvent(input1, 'input');
    var obs2 = fromEvent(input2, 'input');
    
    var obs1 = fromEvent(input1, 'input');
    var obs2 = fromEvent(input2, 'input');
    
    obs1.pipe(mergeMap(event1 => obs2.pipe(
          map(event2 => (<HTMLInputElement>event1.target).value
            + " "
            + (<HTMLInputElement>event2.target).value))))
          .subscribe((result) => {
           span.textContent=result;
          })
    

    【讨论】:

      【解决方案3】:

      导入单个运算符,然后使用管道而不是链接。

      import { map, filter, catchError, mergeMap } from 'rxjs/operators';
      
      source.pipe(
        map(x => x + x),
        mergeMap(n => of(n + 1, n + 2).pipe(
          filter(x => x % 1 == 0),
          scan((acc, x) => acc + x, 0),
        )),
        catchError(err => of('error found')),
      ).subscribe(printResult);
      

      来源:https://auth0.com/blog/whats-new-in-rxjs-6/

      【讨论】:

        【解决方案4】:

        感谢@martin 给出的答案,我能够让它与rxjs6 中的新pipe 操作一起工作。这是我的工作代码。

        import {from, Observable} from 'rxjs';
        import {mergeMap} from 'rxjs/operators';
        
        export class Test {
        
            public doSomething(): Observable<any> {
                return from(...).pipe(mergeMap(...));
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2018-01-28
          • 2017-04-01
          • 1970-01-01
          • 2017-02-27
          • 2018-11-03
          • 2018-12-05
          • 1970-01-01
          • 2022-07-20
          • 1970-01-01
          相关资源
          最近更新 更多