Angular 7升级:RxJs switchMap和ObservableInput <void>的返回类型

时间:2018-10-21 12:30:30

标签: angular rxjs angular7

此代码在Angular 6中编译并工作:

import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

switchMap((term) => {
                if (term.trim().length > 3)
                    return this.searchEntries(term); // <- returns  Observable<void> 

                return of([]);
            })

升级到Angular 7后,出现此编译时错误:

[ts]
Argument of type '(term: any) => Observable<void> | Observable<any[]>' is not assignable to parameter of type '(value: any, index: number) => ObservableInput<void>'.
  Type 'Observable<void> | Observable<any[]>' is not assignable to type 'ObservableInput<void>'.
    Type 'Observable<any[]>' is not assignable to type 'ObservableInput<void>'.
      Type 'Observable<any[]>' is not assignable to type 'Iterable<void>'.
        Property '[Symbol.iterator]' is missing in type 'Observable<any[]>'.

角度版本:

$ ng version

Angular CLI: 7.0.2
Node: 10.12.0
OS: linux x64
Angular: 7.0.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.2
@angular-devkit/build-angular     0.10.2
@angular-devkit/build-optimizer   0.10.2
@angular-devkit/build-webpack     0.10.2
@angular-devkit/core              7.0.2
@angular-devkit/schematics        7.0.2
@angular/cli                      7.0.2
@ngtools/webpack                  7.0.2
@schematics/angular               7.0.2
@schematics/update                0.10.2
rxjs                              6.3.3
typescript                        3.1.3
webpack                           4.19.1

看起来我必须为switchMap返回ObservableInput,但是如何?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

感谢@cartant,我通过添加如下返回类型解决了编译时错误:

switchMap((term) : Observable<void | any[]> => {
                if (term.trim().length > 3)
                    return this.searchEntries(term); // <- returns  Observable<void> 

                return of([]);
            })