Angular Error_for_TS2554预期有0个参数,但有3个

时间:2019-07-13 16:18:36

标签: angular rxjs6 angular8

为所有呼叫创建通用的httpServie。

  export class HttpApiService {
    constructor( private httpClient: HttpClient) {}
    public getData<T>(url: string, headers?: HttpHeaders): Observable<T> | Observable<any> {
        this.customReqOptions = this.getHeaders(headers);
        return this.httpClient.get(`${this.endPoint}${url}`, { headers: this.customReqOptions});
    }
  }

从UserSevice调用

export class UserService {
    constructor(private httpApi: HttpApiService) {
    }

    public getUsers(): Observable<any>{
      return this.httpApi.getData('users')
      .pipe(
        tap((res) => {console.log('res,',res)}),
        publishReplay(1),
        refCount()
      );
    }
}

给出错误TS2554的管道()一:预期为0,但得到3。

为引用https://stackblitz.com/edit/anglearn

创建了代码

即使在VS代码中运行时也遇到同样的问题 enter image description here

我缺少什么? 尽管使用的是最新版本@angular:v8,rxjs:6.4使用ngcli。

2 个答案:

答案 0 :(得分:0)

像这样更改您的getData方法:

public getData<T>(url: string, headers?: HttpHeaders): Observable<T> {
        this.customReqOptions = this.getHeaders(headers);
        return this.httpClient.get<T>(`${this.endPoint}${url}`, { headers: this.customReqOptions});
    }

由于某些原因,TS编译器不喜欢通用方法返回Observable<any>。注意-没有运行时错误。

查看有效的堆叠闪电-https://stackblitz.com/edit/anglearn-tezbyk?file=src/app/common/httpApi.service.ts

答案 1 :(得分:0)

添加所有签名/重载

    public getData(url: string, headers?: HttpHeaders): Observable<any>;
    public getData<T>(url: string, headers?: HttpHeaders): Observable<T>;
    public getData<T>(url: string, headers?: HttpHeaders): Observable<T> | Observable<any> {
        this.customReqOptions = this.getHeaders(headers);
        return this.httpClient.get(`${this.endPoint}${url}`, { headers: this.customReqOptions});
    }

VScode(运行/编译)中没有问题。不确定是否是一种好的做法。