Angular 12 HttpClient POST返回纯字符串时代码无法编译如何解决
问题原因
你同时给post方法指定了泛型参数<string>和responseType: 'text',导致TypeScript没有匹配到正确的HttpClient.post重载,反而错误匹配到了返回ArrayBuffer的重载,才会出现类型不兼容的报错。
Angular的HttpClient针对不同的responseType有独立的重载定义:
- 带泛型
<T>的重载默认对应responseType: 'json'的场景,返回Observable<T> - 当
responseType显式设为'text'时,对应无泛型的专用重载,本身就已经定义了返回值为Observable<string>,不需要额外加泛型声明
正确代码
直接移除post方法后的<string>泛型参数即可:
public ping(): Observable<string> { return this.httpClient.post(this.uri, {}, { observe: 'body', responseType: 'text' }); }
如果你的TypeScript版本较低仍然出现匹配问题,可以额外给options增加类型断言辅助识别:
public ping(): Observable<string> { return this.httpClient.post(this.uri, {}, { observe: 'body', responseType: 'text' } as const); }
内容的提问来源于stack exchange,提问作者usr-local-ΕΨΗΕΛΩΝ
相关产品推荐
相关产品推荐

