Angular 6-使用http.get responseType:ResponseContentType.Blob时出错

时间:2018-08-22 22:46:50

标签: angular angular5 angular6 httpclient response

我想在(角度5)中做一个这样的观察。 如何在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) => { 

我的角度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"'.

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

我正在尝试下载Excel方法!

5 个答案:

答案 0 :(得分:3)

解决方法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; 
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

尝试一下。对我来说很好...

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

This is how we can add responseType in Angular 6+ versions,

const httpOptions = {
     headers: new HttpHeaders({
     'Content-Type': 'application/json'
     }),
     observe: 'response' as 'body',
     responseType: 'blob' as 'blob'
};

return this.httpClient.get("API_URL", httpOptions);

For more, you can refer here.