Issue
Angular 2 how to return from map if it has subscription inside
getImage(imageId: string): Observable<ImageSource> {
return this.http.get(`${ImagesUrl}/${imageId}`, {
responseType: 'blob', observe: 'response' }).map((response) => {
// here I am converting blob to base64
let blob = response; // lets say response is blob
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = (e) => {
// how can I return from here?????
};
}
}
is there a way to return from map only after onloadend event?
Solution
I do not know FileReader class, but you can try to chain all the things you have to do (utilize streams).
function getImage(imageId: string): Observable<ImageSource> {
return this.http.get(`${ImagesUrl}/${imageId}`, {responseType: 'blob', observe: 'response'})
.switchMap((response) => {
const blob = response;
const reader = new FileReader();
reader.readAsDataURL(blob);
return Observable.fromPromise(new Promise((resolve, reject) => {
reader.onloadend = resolve;
}));
});
}
reader.onloadend = resolve;
is a shorthand for
reader.onloadend = (e) => { resolve(e); }
At the end of stream you will get event published by onloadend
. If you need anything else, just pass another argument to resolve.
You should also handle case when something fails with reject
.
Answered By - Łukasz Szcześniak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.