从 Observable 到 return 布尔值的最简单方法
Simplest way to return boolean from Observable
我想为 canActivate() 方法获取布尔值,但没有任何效果。
我的代码是:
login() {
return this.http.get<any>('http://localhost/auth');
}
我想做这样的事情:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authenticationService.login().subscribe(
() => true,
() => false
);
}
正确的做法是什么?
你不需要在 canActivate
方法中订阅 Guard 路由:事实上,Guard 可以 return Observable 并且 Angular 会订阅它。
只需要使用rxjs的map
运算符,比如:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authenticationService.login().pipe(
map(response => /* do your stuff and return true to allow route access */)
catchError(error => of(false)) // Auth failed : return false to prevent route access
)
}
查看更多here
我想为 canActivate() 方法获取布尔值,但没有任何效果。 我的代码是:
login() {
return this.http.get<any>('http://localhost/auth');
}
我想做这样的事情:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authenticationService.login().subscribe(
() => true,
() => false
);
}
正确的做法是什么?
你不需要在 canActivate
方法中订阅 Guard 路由:事实上,Guard 可以 return Observable 并且 Angular 会订阅它。
只需要使用rxjs的map
运算符,比如:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authenticationService.login().pipe(
map(response => /* do your stuff and return true to allow route access */)
catchError(error => of(false)) // Auth failed : return false to prevent route access
)
}
查看更多here