首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >参数“source”和“source”的类型不兼容

参数“source”和“source”的类型不兼容
EN

Stack Overflow用户
提问于 2020-05-05 18:33:48
回答 2查看 1.7K关注 0票数 0

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

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

我返回一个错误:

代码语言:javascript
复制
     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,typescript 3.7.5。

更新:

这是我的handleError:

代码语言:javascript
复制
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);
}
EN

回答 2

Stack Overflow用户

发布于 2020-05-05 19:09:41

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

代码语言:javascript
复制
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)
  );
票数 0
EN

Stack Overflow用户

发布于 2020-05-05 19:53:42

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

代码语言:javascript
复制
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的返回类型

代码语言:javascript
复制
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)
  );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61611078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档