Angular 5.2 Custom HttpClient类 - 无法将responseType更改为blob

问题描述 投票:0回答:2

我在我的项目中使用Angular 5.2版本,并在使用新函数将默认responseType更改为blob时遇到问题。

现在我想将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);
    }
}

现在我想调用GetBlob函数并将responseType更改为'blob'。但它显示错误“类型”blob“不能分配给类型”Json“”。

从组件服务类,我这样调用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);
}
angular angular5 angular-httpclient
2个回答
1
投票

最近有同样的问题,希望他们能解决一段时间。我使用Object.assign作为解决方法:

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

这样你可以欺骗ts类型检查。


0
投票

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

  export interface IRequestOptions {

    headers?: HttpHeaders;
    observe?: 'body';
    params?: HttpParams;
    reportProgress?: boolean;
    responseType?: string;
    withCredentials?: boolean;
    body?: any;
}
© www.soinside.com 2019 - 2024. All rights reserved.