【问题标题】:Angular 6 - Error using http.get responseType: ResponseContentType.BlobAngular 6 - 使用 http.get responseType 时出错:ResponseContentType.Blob
【发布时间】:2018-08-22 22:46:50
【问题描述】:

我想在 (angular 5) 中制作一个像这样的 observable。 如何在 Angular 6 中声明 responseType

Angular 5 代码:

public ExportSomeThing(
        ano: number
    ): Observable<IDownloadArquivo> {
        let q = this.http
            .get(this.apiUrl + ano + '/pordia/excel', {
                responseType: ResponseContentType.Blob  // <<<-- This code
            }).map((res) => { 

我的 Angular 6 代码:

public MyExport(
    ano: number
  ): Observable<IXpto> {
    let q = this.http
      .get( this.api_rul + ano + '/some_path/', {
        responseType: "ResponseContentType.Blob"  // <<<--- error here !!!
      }).map((res) => {

错误是:

[ts]
Argument of type '{ responseType: "ResponseContentType.Blob"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'.
  Types of property 'responseType' are incompatible.
    Type '"ResponseContentType.Blob"' is not assignable to type '"json"'.

如何使我的 http.get 在 Angular 6 中相似?

我正在尝试下载Excel方法!

【问题讨论】:

  • 显然枚举已被弃用,正如它在枚举描述中所说的那样。现在写responseType: 'blob' 就足够了。注意不要在 get/post 方法调用中使用泛型参数,因为现在返回类型很明显不需要泛型参数。任何来这里的人都可以看到:angular.io/guide/http#requesting-non-json-data

标签: angular angular5 angular6 httpclient response


【解决方案1】:

解决方法 Angular 8

客户端:

 getBlob(url: string): Observable<Blob> {
        return this.http.get<Blob>(url, { observe: 'body', responseType: 'blob' as 'json' })
 }

注意 'blob' 作为 'json' 技巧

服务器端返回字节[]:

@GetMapping(value = "/api/someApi")
public @ResponseBody byte[] GetBlob() {

     byte[] ret  = this.service.getData();
     return ret; 
}

【讨论】:

    【解决方案2】:

    here 给出了很好的解释。试试下面的代码

      public getRequest(urlPath: string): Observable<any> {
    
        const options = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'Authorization': token  // if you have to give token
            }),
    
            // Ignore this part or  if you want full response you have 
            // to explicitly give as 'boby'as http client by default give res.json()
            observe:'response' as 'body',
    
           // have to explicitly give as 'blob' or 'json'
            responseType: 'blob' as 'blob'  
        };
    
         // resObj should be of type Blob
        return this.http.get(urlPath, options)
            .map((resObj: Blob) => resObj)
            .catch((errorObj: any) => Observable.throw(errorObj || 'Server error'));
    }
    

    【讨论】:

      【解决方案3】:

      将“ResponseContentType.Blob”替换为“blob”

      this.http.get( this.api_rul + ano + '/some_path/', {
          responseType: 'blob'
        }).map((res) => {})
      

      【讨论】:

        【解决方案4】:

        这就是我们在 Angular 6+ 版本中添加 responseType 的方法,

        const httpOptions = {
             headers: new HttpHeaders({
             'Content-Type': 'application/json'
             }),
             observe: 'response' as 'body',
             responseType: 'blob' as 'blob'
        };
        
        return this.httpClient.get("API_URL", httpOptions);
        

        更多内容可以参考here

        【讨论】:

          【解决方案5】:

          试试这个。很适合我...

          public post(data?: any, useHeaders: boolean = true, contentType: HttpContentTypeEnum = HttpContentTypeEnum.Json, responseType: HttpResponseTypeEnum = HttpResponseTypeEnum.Json): Observable<any> {
          
              try {
          
                  if (useHeaders) {
          
                      let resonseType: any;
                      let headers: HttpHeaders;
          
                      switch (contentType) {
          
                          case HttpContentTypeEnum.Json: {
          
                              headers = new HttpHeaders({ "Content-Type": "application/json" });
          
                              break;
                          }
                      }
          
                      switch (responseType) {
          
                          case HttpResponseTypeEnum.Text: {
          
                              resonseType = 'text';
          
                              break;
                          }
          
                          case HttpResponseTypeEnum.Json: {
          
                              resonseType = 'json';
          
                              break;
                          }
          
                          case HttpResponseTypeEnum.Blob: {
          
                              resonseType = 'blob';
          
                              break;
                          }
                      } 
          
                      return this.http.post(this._baseUri, data, { responseType: resonseType, headers: headers }).pipe(catchError((err: any) => {
                          if (err.status === 401) {
          
                              return Observable.throw('Unauthorized');
                          }
                      }));
                  }
                  else {
          
                      return this.http.post(this._baseUri, data).pipe(catchError((err: any) => {
                          if (err.status === 401) {
          
                              return Observable.throw('Unauthorized');
                          }
                      }));
                  }
              } catch (err) {
          
                  //console.log((<Error>e).message);
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2019-08-18
            • 2019-03-21
            • 2016-11-08
            • 2015-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-15
            • 2019-10-26
            相关资源
            最近更新 更多