我在项目中使用的是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);
}
答案 0 :(得分:1)
最近有同样的问题,希望他们能在一段时间后解决。 我使用Object.assign作为解决方法:
public class UARTCommunicationProvider
{
SerialDevice _serialPort;
private DataReader _serialPortReader;
private DataWriter _serialPortWriter;
private CancellationTokenSource _serialPortReadWriteCTS = null;
public UARTCommunicationProvider()
{
_serialPortReadWriteCTS = new CancellationTokenSource();
}
public async Task<bool> ConnectAsync(string comportId)
{
_serialPort = await SerialDevice.FromIdAsync(comportId);
if (_serialPort != null)
{
_serialPort.WriteTimeout = TimeSpan.FromMilliseconds(50);
_serialPort.ReadTimeout = TimeSpan.FromMilliseconds(50);
_serialPort.BaudRate = 9600;
_serialPort.Parity = SerialParity.None;
_serialPort.StopBits = SerialStopBitCount.One;
_serialPort.DataBits = 8;
_serialPort.Handshake = SerialHandshake.None;
_serialPortReader = new DataReader(_serialPort.InputStream);
// Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
_serialPortReader.InputStreamOptions = InputStreamOptions.Partial;
_serialPortWriter = new DataWriter(_serialPort.OutputStream);
return true;
}
else
{
return false;
}
}
public async void CollectData()
{
var command = "FL 1\n";
while (true)
{
var response = await ResponseForCommandAsync(command);
Debug.WriteLine(response)
}
}
public void Disconnect()
{
try
{
_serialPort?.Dispose(); //Stuck at this point when I try to dispose after reading few chunks of data from serial port
_serialPortReadWriteCTS.Cancel();
_serialPort = null;
}
catch (Exception ex)
{
throw;
}
}
public async Task<string> ResponseForCommandAsync(string command)
{
string response = string.Empty;
if (_serialPort != null)
{
// Load the text from the sendText input text box to the dataWriter object
_serialPortWriter.WriteString(command);
UInt32 bytesWritten = await _serialPortWriter.StoreAsync();
if (bytesWritten > 0)
{
bytecount = bytecount + (int)bytesWritten;
_logger.WriteLine("Data Sent Successfully", AEIoTCommon.Common.LoggingType.Verbose);
response = await ReadAsync();
}
}
return response;
}
private async Task<string> ReadAsync()
{
string valueRead = null;
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 1024;
try
{
CancellationToken cancellationToken = _serialPortReadWriteCTS.Token;
//If task cancellation was requested, comply
cancellationToken.ThrowIfCancellationRequested();
using (var childCancellationTokenSource = new CancellationTokenSource(3000))
{
// Create a task object to wait for data on the serialPort.InputStream
loadAsyncTask = _serialPortReader.LoadAsync(ReadBufferLength).AsTask(childCancellationTokenSource.Token);
// Launch the task and wait
UInt32 bytesRead = await loadAsyncTask;
if (bytesRead > 0)
{
//byte[] buffer = new byte[bytesRead];
var value = _serialPortReader.ReadString(bytesRead);
valueRead = value;
}
}
}
catch (TaskCanceledException ex)
{
Disconnect();
}
return valueRead;
}
}
这样您就可以作弊ts类型检查。
答案 1 :(得分:0)
尝试更改您的IRequestOptions接口,以使响应类型为字符串类型。 像这样:
export interface IRequestOptions {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType?: string;
withCredentials?: boolean;
body?: any;
}