类型“Observable<unknown>”不可分配给类型“Observable<ApiResponse>”

use*_*334 0 typescript angular

在 Angular 项目中,我在服务中定义了一个函数,该函数应该调用我的 API。

\n

这个函数看起来像这样:

\n
apiCall(type: string, path: string, params: string[], data: any, headers?: HttpHeaders) {\nlet result = new Observable();\nresult = this.http.get(API_URL + '/' + path, {headers});\n\nreturn result.pipe(\n      tap(\n        (response: ApiResponse) => {\n          // console.log(response);\n          return {...response};\n        }),\n      catchError(this.handleError())\n    );\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但是,在最后一行代码中,我收到以下错误:

\n
TS2345: Argument of type 'MonoTypeOperatorFunction<ApiResponse>' is not assignable to parameter of type 'OperatorFunction<unknown, ApiResponse>'. \xc2\xa0\xc2\xa0Types of parameters 'source' and 'source' are incompatible. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type 'Observable<unknown>' is not assignable to type 'Observable<ApiResponse>'. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type 'unknown' is not assignable to type 'ApiResponse'.\n
Run Code Online (Sandbox Code Playgroud)\n

我试图搜索这个错误,但我没有在任何地方找到解决方案。

\n

奇怪的是,同样的代码在其他项目中工作,所以我不明白出了什么问题

\n

Twi*_*her 5

通过做这个:

let result = new Observable();
result = this.http.get(API_URL + '/' + path, {headers});
Run Code Online (Sandbox Code Playgroud)

您正在分配一个新的Observable,然后将其替换Observable为 Angular 框架中的另一个。除了毫无用处之外,TypeScript 还result从它的第一个赋值中推断出 的类型:Observable<unknown>

所以就这样写:

const result = this.http.get<ApiResponse>(API_URL + '/' + path, { headers });
Run Code Online (Sandbox Code Playgroud)