【问题标题】:Types of parameters 'source' and 'source' are incompatible参数 'source' 和 'source' 的类型不兼容
【发布时间】:2020-05-08 15:54:46
【问题描述】:

我正在尝试使用以下 getFoo 函数访问 foo.json 文件中的数据。

    getFoo(): Observable<IFoo[]> {
      return this.http.get<IFoo[]>(this.fooUrl).pipe(
      tap(data => console.log('All: ' + JSON.stringify(data))),
      catchError(this.handleError)
      );
   }

我返回一个错误:

     Argument of type 'UnaryFunction<Observable<IFoo[]>, Observable<IFoo[]>>' is 
     not assignable to parameter of type 'OperatorFunction<IFoo[], IFoo[]>'.
     Types of parameters 'source' and 'source' are incompatible.
     Type 'Observable<IFoo[]>' is missing the following properties from type 
    'Observable<IFoo[]>': buffer, bufferCount, bufferTime, bufferToggle, and 104 more.

不完全确定如何解决此问题。

运行 Angular 9.0.3,打字稿 3.7.5。

更新:

这是我的句柄错误:

private handleError(err: HttpErrorResponse) {

  let errorMessage = '';
  if (err.error instanceof ErrorEvent) {
    errorMessage = `An error occurred: ${err.error.message}`;
  } else {

    errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
  }
  console.error(errorMessage);
  return _throw (errorMessage);
}

【问题讨论】:

  • 能否也分享一下你的this.handleError函数的代码?
  • 更新了问题以包含它
  • 你用的是什么 rxjs 版本?
  • 你从两个不同的地方导入了两个不同的 Observable,它们不兼容。检查您的导入并确保您仅使用该库的单个实例。
  • 你还在面对这个问题吗?

标签: angular typescript rxjs angular-observable


【解决方案1】:

这应该是正确的版本(在 get 上没有泛型并带有 map 函数):

import { map } from 'rxjs/operators';
...

getFoo(): Observable<IFoo[]> {
  return this.http.get(this.fooUrl).pipe(
  // tap(data => console.log('All: ' + JSON.stringify(data))),
  map<any, IFoo[]>(data => {
    console.log('All: ' + JSON.stringify(data)); 
    return data;
  }),
  catchError(this.handleError)
  );

【讨论】:

  • 感谢您的评论,不幸的是出现了同样的错误。
【解决方案2】:

由于您使用的是最新版本的 Angular 之一,它应该使用 RxJS 6+。 _throw 已被throwError 取代:

private handleError(err: HttpErrorResponse) {

  let errorMessage = '';
  if (err.error instanceof ErrorEvent) {
    errorMessage = `An error occurred: ${err.error.message}`;
  } else {
    errorMessage = `Server returned code: ${err.status}, error message is: 
   ${err.message}`;
  }
  return throwError(errorMessage);
}

如果上述方法仍然不能解决问题,您将需要修复 getFoo 以使所有路径实际上都返回类型为 IFoo[] 的 observable,因为它被声明为 getFoo 的返回类型

getFoo(): Observable<IFoo[] | HttpErrorResponse> {
  return this.http.get<IFoo[]>(this.fooUrl).pipe(
  map(data => {
    console.log('All: ' + JSON.stringify(data));
    return data;
  }),
  catchError(this.handleError)
  );
}

【讨论】:

    猜你喜欢
    • 2018-07-08
    • 2022-08-22
    • 2021-07-22
    • 2012-05-26
    • 2023-01-23
    • 2013-07-02
    • 1970-01-01
    • 2017-04-29
    • 2019-12-27
    相关资源
    最近更新 更多