Front End: Angular 4
Back End: Java(RestFul Web Service)
My rest call returns a excel as response. I have written the code to return that same file to the user.
My Controller:
exportExcelXSL() {
var excelData;
console.log("Excel");
console.log(this.workRequestSearchBasicReq);
this.workRequestSearchBasicReq.OrdersPerPage = undefined;
let request = Utility.removeUndefinedNullFields(this.workRequestSearchBasicReq);
console.log(request);
var data = {};
data["ICWRQry"] = Utility.removeUndefinedNullFields(request);
this.workRequest.workRequestReport(data).subscribe(data => {
var mediaType = 'application/vnd.ms-excel';
let blob: Blob = data.blob();
window['saveAs'](blob, 'sample.xls');
});
this.cd.detectChanges();
}
My Service:
workRequestReport(searchOrderReq: any): Observable<Blob> {
let workRequestSearchBeanShellUrl = "http://localhost:7001/uuigui/uui/eapp/iVAPP/WorkRequestSearchReport";
return this.httpClient.post(workRequestSearchBeanShellUrl, searchOrderReq, {
headers: new HttpHeaders({'responseType': 'ResponseContentType.Blob '})
}).map(data => data.blob());
}
But in console, I am getting error as «property ‘blob’ does not exist on type ‘Object'» error in both Service(Line:map(data => data.blob());)
& Controller(Line:let blob: Blob = data.blob();)
Can somebody help me to fix this issue?
Thanks in advance.
Hi,
When the responseType is blob, the error response is converted into a blob as well.
Is there a way to specify a different responseType for errors?
That isn’t supported for the moment but you can implement it yourself specifying a custom transformResponse
function.
I’m running into the exact same issue. Server returns a blob on success, on error a JSON object is returned containing error details.
The data returned in the transformResponse function is typed to the responseType (responseType blob
: data is an [object Blob]
), and there’s no context available to know if the request succeeded or not.
An example how to know if the request succeeded and transform it to JSON if it didn’t would be greatly appreciated.
@nickuraltsev since I can’t re-open this issue, any guidance on how we can handle this situation?
Same issue for me. I’d like to be able to use a solution like the one referenced here: https://stackoverflow.com/a/29039823
But it requires access to the onreadystatechange event of XMLHttpRequest, which isn’t exposed. TransformResponse doesn’t work since it’s too late.
+1 for this, I had a hack for it:
// Here is a hack, works well for me. // You can put it into `transformResponse`, etc as well. import fileDownload from 'js-file-download' opts.responseType = 'blob' // <--- force blob at the beginning, anyway res = await axios(opts) let resBlob = res.data // <--- store the blob if it is let resData = null try { let resText = await new Promise((resolve, reject) => { let reader = new FileReader() reader.addEventListener('abort', reject) reader.addEventListener('error', reject) reader.addEventListener('loadend', () => { resolve(reader.result) }) reader.readAsText(resBlob) }) resData = JSON.parse(resText) // <--- try to parse as json evantually } catch (err) { // ignore } // Now you have `resData` and `resBlob` at the same time. // `resData` would be the normal data object, // or the error object if `resBlob` is expected. if (resData) { if (resData.error) { // handle error } else { // handle data } } else { // handle blob fileDownload(resBlob, filename) }
#448 (comment) looks like a full-typed version and more thoughtful but needs to take error-handling into account
chimmelb and gloria912 reacted with hooray emoji
TheProudSoul and Panpan0403 reacted with heart emoji
@fritx works perfect, but indeed a bit hacky. @nickuraltsev any ideas how to improve this? thanks!
@fritx Your workaround worked for me on a blob image sent as response. Thanks.
Using ArrayBuffer is another option, and do not need to solve the problem that synchrounsly read content of file blob.
const service = axios.create(); service.interceptors.response.use( response => { if (!/json$/gi.test(response.headers['content-type'])) { /** not json, like binary string */ return response.data; } if (response.request.responseType === 'arraybuffer' && response.data.toString() === '[object ArrayBuffer]' ) { /** error response */ const res = JSON.parse(Buffer.from(response.data).toString('utf8')); } /** handle res according to the JSON object */ /** ... */ }, error => {/** handle error response status */} ); const downloader = require('js-file-download'); server.post(url, params, { responseType: 'arraybuffer', }).then(data => { downloader(data, 'xxx.csv'); });
In case of error response with json:
let axios = ...instantiate...;
axios.interceptors.response.use(
response => { return response; },
error => {
if (
error.request.responseType === 'blob' &&
error.response.data instanceof Blob &&
error.response.data.type &&
error.response.data.type.toLowerCase().indexOf('json') != -1
)
{
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => {
error.response.data = JSON.parse(reader.result);
resolve(Promise.reject(error));
};
reader.onerror = () => {
reject(error);
};
reader.readAsText(error.response.data);
});
};
return Promise.reject(error);
}
);
TomasNiDo reacted with hooray emoji
a-mujthaba321 reacted with heart emoji
a-mujthaba321 reacted with rocket emoji
axios
locked and limited conversation to collaborators
May 22, 2020
Loading
So I am trying a video chat code that I’ve found on youtube but when I try to establish I call I end up with this error .it’s been n a few days now and I don’t know where is the issue
here is the code
private localStream: MediaStream;
inCall = false;
localVideoActive = false;
constructor(private dataService: DataService) { }
async call(): Promise<void> {
this.createPeerConnection();
// Add the tracks from the local stream to the RTCPeerConnection
this.localStream.getTracks().forEach(
track => this.peerConnection.addTrack(track, this.localStream)
);
try {
const offer: RTCSessionDescriptionInit = await this.peerConnection.createOffer(offerOptions);
// Establish the offer as the local peer's current description.
await this.peerConnection.setLocalDescription(offer);
this.inCall = true;
this.dataService.sendMessage({type: 'offer', data: offer});
} catch (err:any) {
this.handleGetUserMediaError(err);
}```
asked Sep 20, 2022 at 12:18
Update you websocket send message as mentioned below
ws.on("message", function message(data, isBinary) {
const message = isBinary ? data : data.toString();
// Continue as before.
console.log(message + "\n\n");
wss.broadcast(ws, message);
});
answered Oct 15, 2022 at 8:34
If you are working with JavaScript or TypeScript, you might come across an error that says “parameter is not of type ‘Blob’”. This error occurs when you are trying to pass a variable that is not of the type Blob to a function that expects a Blob parameter.
Common Causes of the Error
The following are some common causes of the error:
- The variable you are trying to pass is not a Blob object.
- The variable you are trying to pass is null or undefined.
- You are trying to pass a file path instead of a Blob object.
Example Code
Here is an example code that can trigger the error:
function uploadFile(file) {
// Some code to upload the file
}
const filePath = "path/to/file.pdf";
uploadFile(filePath);
In the code above, the `uploadFile` function expects a Blob object as a parameter, but we are passing a file path string instead. This will result in the “parameter is not of type ‘Blob’” error.
Here is the correct way to pass a Blob object:
function uploadFile(file) {
// Some code to upload the file
}
const fileBlob = new Blob(["Hello, world!"], { type: "text/plain" });
uploadFile(fileBlob);
In the code above, we create a Blob object using the `new Blob()` constructor and pass it to the `uploadFile` function as a parameter.
Conclusion
In conclusion, the “parameter is not of type ‘Blob’” error occurs when you try to pass a variable that is not of the type Blob to a function that expects a Blob parameter. You can avoid this error by ensuring that you pass a valid Blob object to the function.