typescript 属性“responseType”的类型不兼容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49771603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:21:07  来源:igfitidea点击:

Types of property 'responseType' are incompatible

angulartypescript

提问by Jitendra Kumar

I am unable to make a POST request in Angular 5 that accepts text/plainas response. Angular is calling a method which expects JSONas response and hence throws an error when response comes while trying to parse the response.

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

I tried calling method with parameter {responseType: 'text'}but VS code is showing it as an error and I am also getting an error in the console when the application is compiled.

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

Below is the Angular 5 code for a POST request that expects a response as text/plain.

以下是 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)
);

While compilation the following error show in the console:

编译时,控制台中显示以下错误:

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"'.

回答by Titian Cernicova-Dragomir

The version of postaccepting responseType:'text'is not generic, since the result type is already clear (ie string)

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)
);

回答by Tanzeel Saleem

Just remove "string" from your request. Try this:

只需从您的请求中删除“字符串”。试试这个:

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

回答by St?ger

I just ran into this particular issue today myself. After searching for a little and figuring that the responseType option shouldexist, I managed to get it work as below:

我今天刚刚遇到了这个特殊的问题。在稍微搜索并确定应该存在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
            });

Setting the responseTypelike that makes it work, compared to configuring it in the 'request' itself.

responseType与在“请求”本身中配置它相比,设置类似使其工作。

Regards.

问候。

回答by atb00ker

Removing <string>or other similar solutions are hacks and I wouldn't recommend it for production.

删除<string>或其他类似的解决方案是黑客行为,我不建议将其用于生产。

Here is a better approach:

这是一个更好的方法:

    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);

Replace textwith valid responseTypeaccording the data that you want to receive.

根据您要接收的数据替换text有效的 responseType

回答by Chandan Kumar

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

Edit

编辑

It is wierd but creating header object separately like below snippet

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

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

would throw error in VS code, so the idea is to pass the entire object in inline post request like above would solve the compilation error.

会在 VS 代码中抛出错误,所以我们的想法是像上面一样在内联 post 请求中传递整个对象将解决编译错误。