【问题标题】:Handling two different types of returns in one call (File(Blob) or JSON) Typscript在一次调用中处理两种不同类型的返回(文件(Blob)或 JSON)打字稿
【发布时间】:2021-05-22 21:50:13
【问题描述】:

这是一个令人困惑的问题,但希望有人能提供帮助。

基本上,我从 Angular 11 中的服务调用 API,它可以返回两件事之一。

  1. 如果 API 正确处理上传的文件,它会向用户返回一个新文件。
  2. 如果 API 没有正确处理上传的文件,它会返回 JSON 给用户

如何编写一个可以处理作为文件的响应或作为 JSON 的响应的请求?我遇到了很多麻烦。

提前致谢。

(我当前的服务请求)

return this._http.post(this.baseUrl, formData, {observe: 'response', responseType: 'blob'});

【问题讨论】:

    标签: angular typescript asp.net-core httprequest httpresponse


    【解决方案1】:

    你应该从服务器返回错误的请求,你可以使用 rxjs 操作符来解决这个问题。 pipe() 函数中使用了 Rxjs 运算符。

    您可以使用 catchError() 操作符https://www.learnrxjs.io/learn-rxjs/operators/error_handling/catch

    处理错误请求

    在 catchError() 运算符中,您应该返回 observable。在这个例子中,我只是返回包含在 observable 中的 null 值。

    return this._http.post(this.baseUrl, formData, {observe: 'response', responseType: 'blob'}).pipe(
      catchError((response: any) => {
        // you can write code here
    
        // you should return with observable
        return of(null);
      }),
    );
    

    【讨论】:

      【解决方案2】:

      你必须在方法的返回类型部分指定这两种类型,如下所示:

      public apiCall(YourParameters): TypeA | TypeB {
        // your code
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-13
        • 1970-01-01
        • 2021-12-17
        • 2019-05-30
        • 2020-08-31
        • 1970-01-01
        • 2021-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多