angular - 属性类型 'responseType' 不兼容

标签 angular typescript

我无法在 Angular 5 中发出接受 text/plain 作为响应的 POST 请求。 Angular 正在调用一个方法,该方法期望 JSON 作为响应,因此在尝试解析响应时出现响应时会抛出错误。

我尝试使用参数 {responseType: 'text'} 调用方法,但 VS code 将其显示为错误,并且在编译应用程序时我也在控制台中收到错误消息。

下面是一个 POST 请求的 Angular 5 代码,它期望响应为 text/plain

this.http
.post<string>(this.loginUrl, this.user, {responseType: 'text'}) // error in this line
.subscribe(
    (data) => this.success(data),
    (error) => this.failure(error)
);

编译时控制台出现如下错误:

ERROR in src/app/login/login.component.ts(47,47): error TS2345: Argument of type '{ responseType: "text"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'responseType' are incompatible.
    Type '"text"' is not assignable to type '"json"'.

最佳答案

接受 responseType:'text'post 版本不是通用的,因为结果类型已经明确(即 string)

this.http
.post(this.loginUrl, this.user, {responseType: 'text'}) // no generic parameter
.subscribe(
    (data) => this.success(data), // data is string
    (error) => this.failure(error)
);

关于angular - 属性类型 'responseType' 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771603/

相关文章:

angular - 如何在 typescript 中声明和处理 float 类型?

javascript - 显示冷却剩余时间

javascript - Angular 2 路由器 : route everything behind a certain route

Angular Mentions - 保存所选用户的 ID 值

HTML <a> 从第二次点击开始跳转到页面的特定部分

angular - 如何在 Angular2 中将 ngModule 路由添加为另一个 ngModule 的子路由?

node.js - 嵌套 Promise 不会将错误传播到 Node.js 中的父 Promise?

java - 如何使用 Angular 从java接收文件csv

javascript - 如何使 FileReader 与 Angular2 一起工作?

typescript - `unknown` 类型被强制为 `string` ,尽管 `unknown` 的官方语义