I have a function below which returns the result as a promise and want to convert it to observable to process it further.
isAuthenticated(): () => Promise<boolean> {
return async () => {
const payload: any = JSON.parse(sessionStorage.getItem('token'));
const isExpired = payload?.token ? this.helper.isTokenExpired(payload.token) : true;
const isAuthenticated = await this.nbAuthService.isAuthenticated().toPromise();
return !isExpired && isAuthenticated;
};
}
And the Observable function:
canActivate(): Observable<boolean> {
const observable = from(this.authService.isAuthenticated());
return observable.pipe(
tap(authenticated => {
if (!authenticated) {
this.router.navigate(['/auth/sign-in']);
}
}),
);
}
It throws an error:
Error: Uncaught (in promise): TypeError: You provided '() => Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function* () { const payload = JSON.parse(sessionStorage.getItem('token')); const isExpired = (payload === null || payload === void 0 ? void 0 : payload.token) ? this.helper.isTokenExpired(payload.token) : true; const isAuthenticated = yield this.nbAuthService.isAuthenticated().toPromise(); return !isExpired && isAuthenticated;
Blockquote
ok how about you change your isAuthenticated function to return an observable like below
isAuthenticated():Observable<boolean> {
return from(this.nbAuthService.isAuthenticated().toPromise())
.pipe(
map(isAuthenticated=>{
const payload: any = JSON.parse(sessionStorage.getItem('token'));
const isExpired = payload?.token ? this.helper.isTokenExpired(payload.token) : true;
return !isExpired && isAuthenticated); })
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.