Reputation: 37
I have this promise based function and im trying to update it to have the same functionality but use RXJS, im a bit new to rxjs and having a lot of trouble.. any help would be really appreciated
public getBase64ImageFromURL(url: string): Promise<any> {
return new Promise((resolve, reject) => {
const img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL('image/png');
resolve(dataURL);
};
img.onerror = error => {
reject(error);
};
img.src = url;
});
}
Upvotes: 0
Views: 76
Reputation: 55754
It's pretty straight forward : create a new Observable
and next
the same value as the resolve
!
public getBase64ImageFromURL(url: string): Observable<string> {
return new Observable<string>((subscriber) => {
const img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL('image/png');
subscriber.next(dataURL);
};
img.onerror = (error) => {
subscriber.error(error);
};
img.src = url;
});
}
Upvotes: 3