Convert Promise to RxJs Observable
Your getToken()
-Method should have some proper error-handling. Calling both resolve()
and reject()
is bad and could lead to unexpected behaviour.
Better do something like this:
getToken(): Promise<any> {
return new Promise<any>((resolve, reject) => {
try {
resolve(JSON.parse(localStorage.getItem('currentUser')).token);
catch(err) {
reject(err);
}
});
}
Having said that getToken2()
should have proper error-handling as well, e.g.:
getToken2(): Rx.Observable<number> {
return Rx.Observable.create(obs => {
try {
obs.next(JSON.parse(localStorage.getItem('currentUser')).token);
catch(err) {
obs.error(err);
}
});
}
You don't need to do all this, just use from()
:
import { from } from 'rxjs';
from(this.authService.getToken())
...
.subscribe(...)
If you want to use a Promise anywhere in an Observable chain you don't even need to convert it to Observable as it happens automatically.
https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875
Apr 2019: Updated for RxJS 6