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

7

我希望在(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方法!


1
枚举已过时,正如枚举描述中所述。现在只需编写 responseType: 'blob' 即可。请注意,不要对 get/post 方法调用使用通用参数,因为现在返回类型是明确的,无需通用参数。任何来到这里的人都可以查看:https://angular.io/guide/http#requesting-non-json-data - mkb
5个回答

6

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

3

这里提供了非常好的解释 链接。请尝试以下代码:

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

1
这是我们在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);

更多信息请参考此处

1

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接