Reputation: 21
I am new to typescript and angular and observables. My question is I have this method that takes a URL and returns the favicon of that URL. How can I use observables instead of promise
getFavIcon(url: string): Promise<any> {
return new Promise((resolve, reject) => {
const hostname = this.getDomain(url);
const src = 'http://' + hostname + '/favicon.ico';
const image = new Image();
image.onerror = () => {
reject({ hasFavourite: false });
};
image.onload = () => {
resolve({ hasFavourite: true, imageURL: src});
};
image.src = src;
});
}
Upvotes: 2
Views: 264
Reputation: 11380
Its creation is quite similar to promise apart from observable can be a continuous stream and you have complete()
it to behave like Promise
getFavIcon(url: string): Promise<any> {
return new Observable((obs) => {
const hostname = this.getDomain(url);
const src = 'http://' + hostname + '/favicon.ico';
const image = new Image();
image.onerror = () => {
obs.error({ hasFavourite: false });
};
image.onload = () => {
obs.next({ hasFavourite: true, imageURL: src});
obs.complete()
};
image.src = src;
});
}
Upvotes: 3