类型'MonoTypeOperatorFunction <any>'的参数不能分配给'UnaryFunction <observable <any>,Observable <any >>'类型的参数

时间:2018-08-02 05:51:08

标签: angular typescript ionic-framework rxjs

我正在尝试从rxjs 5迁移到6,但是我遇到了困难。当我尝试这个

this._connectivity.isOnline().pipe(first()).subscribe((state) => {
  this.syncCheck(user.uid);
});

我遇到此错误

Argument of type 'MonoTypeOperatorFunction<any>' is not assignable to parameter of type 'UnaryFunction<Observable<any>, Observable<any>>'.
  Types of parameters 'source' and 'source' are incompatible.
    Type 'import("/home/User/Desktop/projectname/node_modules/rxjs/Observable").Observable<any>' is not assignable to type 'import("/home/User/Desktop/projectname/node_modules/rxjs/internal/Observable").Observable<a...'.
      Property 'map' is missing in type 'Observable<any>'.

4 个答案:

答案 0 :(得分:4)

对于isOnline()返回类型,您似乎导入错误。确保始终从rxjs导入,而不从rxjs/internal甚至从rxjs/internal/Observable导入。 (必须从first()导入rxjs/operators之类的运算符)

答案 1 :(得分:2)

在一种HTTP服务方法中使用管道时,我遇到了类似的错误(请参阅底部的示例)。问题是在订阅中使用的回调函数缺少键入。在您的情况下,请在any上添加键入内容(不是最好的主意,甚至是state)或删除括号:

解决方案1:

this._connectivity.isOnline()
  .pipe(first()).subscribe((state: any) => {
    this.syncCheck(user.uid);
});

解决方案2:

this._connectivity.isOnline()
  .pipe(first()).subscribe(state => {
    this.syncCheck(user.uid);
});

回到我的案例,我已经使用管道来记录数据。它需要将两种可能的类型设置为可观察的,然后才可以键入回调函数:

  public getPrice(): Observable<string | PriceDTO> {
    return this.http.get<PriceDTO>(`api/price)
      .pipe(
        tap((data: PriceDTO) => console.log('PRICE: ', data)),
        catchError((val: Error) => of(`I caught: ${val}`))
      );
  }

答案 2 :(得分:1)

我在代码中发现了相同的错误:

let source = of([1, 2, 3, 45, 56, 7, 7])
    .pipe(
        filter((x: number) => x % 2 == 0)
    );

TS2345:“ MonoTypeOperatorFunction”类型的参数不能分配给“ OperatorFunction”类型的参数。

要解决此问题,请从过滤器功能中删除类型

 filter(x => x % 2 == 0)

现在您有错误

算术运算的左侧必须为'any','number'类型,因此请确保此烦人的过滤器获得正确的数据类型

filter(x => Number(x) % 2 == 0) // parse element to number

但是现在代码停止工作了。最后,要解决此问题,请从一开始就将from更改为。

let source = from([1, 2, 3, 45, 56, 7, 7])
    .pipe(
        filter((x: number) => Number(x) % 2 === 0)
    )

let source = of(1, 2, 3, 45, 56, 7, 7)
.pipe(
        filter((x: number) => Number(x) % 2 === 0)
    )

所以,导致错误的原因是我的初始数据结构。

我认为,我的示例可以帮助您解决类似的问题。

答案 3 :(得分:1)

我遇到了这样的问题,第一次扫描无法正常工作, 所以我 更改

  .pipe(scan((count ) => count + 1, 0))...

收件人

  .pipe(scan((count:any ) => count + 1, 0))

然后,问题还在于该应用程序的父文件夹中也安装了Rxjs。因此,消除此错误,我相信已经解决了问题。

使用npm-check软件包对于清除npm软件包的全局和本地级别的问题都是一个好主意。