代码之家  ›  专栏  ›  技术社区  ›  Karan

Angular 5.2自定义HttpClient类-无法将responseType更改为blob

  •  0
  • Karan  · 技术社区  · 7 年前

    现在我想把responseType改成blob来下载excel文件,但它对我不起作用。

    在我的项目中,我创建了包装类CustomHttpClient来进行Get或Post调用。

    CustomHttpClient类如下所示:-

        export interface IRequestOptions {
    
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
        body?: any;
    }
    
    
    /*Custom HttpClient Class for making the WebAPI calls.*/
    export class CustomHttpClient {
    
        _defaultHeaderType = new HttpHeaders({ 'Content-Type': 'application/json' });
    
        // Extending the HttpClient through the Angular DI.
        public constructor(public _http: HttpClient) {
    
        }
    
      public Get<T>(endPoint: string, options?: IRequestOptions): Observable<T> {
            if (options == undefined) {
                options = <IRequestOptions>{};
                options.headers = this._defaultHeaderType
            }
    
            options.headers = this.injectClient(options.headers);
            return this._http.get<T>(endPoint, options);
        }
    
        public GetBlob<T>(endPoint: string, options?: IRequestOptions): Observable<T> {
            if (options == undefined) {
                options = <IRequestOptions>{};
                options.headers = this._defaultHeaderType
            }
    
            //This line is giving error
             options.responseType = 'blob';
    
            options.headers = this.injectClient(options.headers);
            return this._http.get<T>(endPoint, options);
        }
    }
    

    在组件服务类中,我这样调用fn:-

    downloadTemplate(): Observable<any> {
        let opt = {
            headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/xlsx'}),
            options: new RequestOptions({ responseType: ResponseContentType.Blob })
        }
    
        return this._httpObj.GetBlob(this._baseUrl + 'DownloadTemplate', opt);
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Oleksandr Martyniuk    7 年前

    最近也有同样的问题,希望以后能解决。

    this._http.get<T>(endPoint, Object.assign(options, { responseType: 'blob' }))
    

        2
  •  0
  •   Shai Aharoni    7 年前

    尝试更改IRequestOptions接口,使响应类型为字符串类型。 这样地:

      export interface IRequestOptions {
    
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType?: string;
        withCredentials?: boolean;
        body?: any;
    }
    
    推荐文章