财产的类型' responseType'是不相容的

时间:2018-04-11 09:37:30

标签: angular typescript

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

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

以下是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"'.

5 个答案:

答案 0 :(得分:14)

post接受responseType:'text'的版本不通用,因为结果类型已经明确(即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)
);

答案 1 :(得分:7)

删除<string>或其他类似解决方案是很容易的事情,我不建议将其用于生产。

这是一种更好的方法:

    const httpOptions = {
      headers: new HttpHeaders({
        'Accept': 'text/plain, */*',
        'Content-Type': 'application/json' // We send JSON
      }),
      responseType: 'text' as 'json'  // We accept plain text as response.
    };
    return this.http.post<string>(this.setBaseUrl, body, httpOptions);

根据您要接收的数据,用valid responseType替换text

答案 2 :(得分:2)

只需从您的请求中删除字符串。 就这样写代码。

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

答案 3 :(得分:0)

this.http.post(this.loginUrl,this.user,{headers:
new HttpHeaders({'content-type':'application/json'}), responseType:'text'})
.subscribe((r)=>{console.log(r)})

修改

很奇怪,但是像下面的代码片段一样单独创建标头对象

let headerOptions = {
 headers: new HttpHeaders(
     {'content-type':'application/json'}),
       responseType:'text'
 }
this.http.post(this.loginUrl,this.user, headerOptions)
 .subscribe((r)=>{console.log(r)})

在VS代码中会引发错误,因此我们的想法是像上述那样在内联的post请求中传递整个对象将解决编译错误。

答案 4 :(得分:0)

我本人今天才遇到这个特殊问题。经过一些搜索并确定了responseType选项应该存在之后,我设法使其工作如下:

let requestOptions: Object = { 
    headers: new HttpHeaders().set('Authorization', 'Basic ' + credentials),
    responseType: 'text'
}    

return this.httpClient.get<any>(
                this.environment.tokenHost + this.environment.authenticationURL,
                requestOptions
            )
            .subscribe(result => {
                // do stuff
            });

与在“请求”本身中进行配置相比,像这样设置responseType使其可以工作。

致谢。

相关问题