Can someone help to convert this promise to an RxJs observable? I want to get token from local storage and if error,it should be catched with observer that subscribed to observable. Below is existing solution with Promise:
getToken(): Promise<any> {
return new Promise<any>((resolve, reject) => {
resolve(JSON.parse(localStorage.getItem('currentUser')).token);
reject();
});
}
and subscriber is :
this.authService.getToken().then(token => {
this.token = token;
}).catch(() => console.log('Error! cannot get token'));
I tried to convert it to Observable with below method :
getToken2(): Rx.Observable<number> {
return Rx.Observable.create(obs => {
obs.next(JSON.parse(localStorage.getItem('currentUser')).token);
obs.error('Error! cannot get token');
});
}
and
this.authService.getToken2()
.subscribe((token) => console.log(token), (er) => console.log(er));
But the problem is that when error occurs while getting token from localstorage ,the RxJs observable does not catch it via obs.next().It is like it is resolved successfully.Whereas Promise catches it successfully via reject method.Can someone give an idea what is wrong? Thanks