I have this method:
isRouteAccessible(token: string): Observable<boolean> {
return this.loginHttpService.isPasswordRecoveryTokenValid(token).subscribe(x => {
if (x) {
return of(true)
}
this.router.navigate(['/authentication/signin'])
return of(false)
})
}
Here is defenition of isPasswordRecoveryTokenValid:
isPasswordRecoveryTokenValid(token: string): Observable<boolean> {
return this.http.get<boolean>(environment.baseUrl '/auth/validateTokenPasswordRecovery', {
params: {
token
}
})
}
I get this error on isRouteAccessible:
Type 'Subscription' is missing the following properties from type 'Observable<boolean>': _isScalar, source, operator, lift, and 6 more.
why do I get this error on isRouteAccessible function?
CodePudding user response:
You're returning a subscription because you have subscribed to an observable, which is different from the return type of 'isRouteAccessible' (Observable).
To solve this, inside 'isRouteAccessible', alter the result from 'isPasswordRecoveryTokenValid', and return the altered result:
isRouteAccessible(token: string): Observable<boolean> {
return this.loginHttpService.isPasswordRecoveryTokenValid(token)
.pipe(
map((x) => { // map the result from 'isPasswordRecoveryTokenValid' to a true/false result
if (x) { // check for whatever result that is returned from the API at /auth/validateTokenPasswordRecovery
return true;
}
this.router.navigate(['/authentication/signin']);
return false;
})
);
}
// then, subscribe to 'isRouteAccessible' like so:
demoCallerFunction() {
this.isRouteAccessible('token').subscribe((result: boolean) => {
console.log(result); // result is either true/false
});
}
Alternavely, if you want to subscribe 'isRouteAccessible', then you have to check and handle the result of 'isPasswordRecoveryTokenValid' inside 'isRouteAccessible' (and don't return a result):
isRouteAccessible(token: string): void {
this.loginHttpService.isPasswordRecoveryTokenValid(token)
.subscribe((x) => {
if (x) { // check for whatever result that is returned from the API at /auth/validateTokenPasswordRecovery
// handle a case of 'true'
return;
}
// handle a case of 'false'
this.router.navigate(['/authentication/signin']);
});
}