【问题标题】:Types of property 'responseType' are incompatible属性“responseType”的类型不兼容
【发布时间】:2021-05-13 22:16:10
【问题描述】:

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

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

下面是 Angular 5 的 POST 请求代码,它期望响应为 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"'.

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

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

    【讨论】:

    • 我还是不明白是什么导致了这个问题?为什么通过添加 .post 可以解决与 reponseType: 'text' 的冲突?
    • @LoganWlv 因为有多个重载,而带有responseType: 'text' 的重载不是泛型的,而泛型的重载只允许'json' 用于responseType
    • 在 Angular 9 中它不适合我,这是我必须做的:stackoverflow.com/a/60693216/6410464
    【解决方案2】:

    如果您不想删除 &lt;string&gt; 以保持您的响应是强类型的,这里有一种方法:

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

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

    【讨论】:

    • 我不明白删除 &lt;string&gt; 比将 responseType 设置为 'text' as 'json' 更像是一种黑客行为。两者在功能上有区别吗?
    • 我不认为应该有功能差异。我将其称为更好方法的唯一原因是在打字稿中,首选明确提及数据类型;这里没有违反。
    • 实际上删除 并不是一种黑客行为,也不违反打字稿的方法。事实上,Angular 的 httpClient 实现决定了如果你使用 resposneType: 'text,那么提供泛型是不必要的,因此这个重载的方法甚至不接受泛型类型。如果有的话,告诉 typescript 将 'text' 视为 'json' 绝对是一种 hack。
    • 'text' as 'json' 是类型断言。由于我希望收到 json,我只是告诉 typescript 的行为就好像结果是 JSON,请搜索关键字 as。在可能的情况下,总是首选保持强类型(请谷歌搜索原因)。如果您不关心类型,请使用anyany 是默认值;它过于宽松,允许对变量进行任何操作;不推荐在可以避免的情况下——省略类型使其成为 any )。我已经删除了hack 这个词,因为我没有时间回复更多关于它的 cmets。干杯。
    【解决方案3】:

    只需从您的请求中删除“string”即可。试试这个:

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

    【讨论】:

    【解决方案4】:

    我今天自己也遇到了这个特殊问题。经过一番搜索并确定 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 使其工作。

    问候。

    【讨论】:

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

      编辑

      这很奇怪,但是像下面的 sn-p 一样单独创建标题对象

      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 请求中的整个对象来解决编译错误。

      【讨论】:

      • 可以添加描述吗?
      • 这解决了我的问题,不知道为什么我们不能单独创建标题选项以实现可重用性等。仅当您想自定义 responseType 时才内联
      • responseType: 'text' as 'text' 当你有一个单独的对象时有效。试一试。
      猜你喜欢
      • 2021-12-06
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 2018-11-21
      相关资源
      最近更新 更多