我已经实现了功能,我能够得到的请求,并控制页面的授权,我想重定向到登录页面的情况下,错误的请求。
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authSer.isAuthenticated().pipe(map((response) => {
console.log('I ma here');
if (response.status === 200) {
return true;
} else {
console.log('Error getting data');
return false;
}
}), catchError((error) => of(false))
);
}如何从此处路由至登录页面?我使用的是angular 6
发布于 2018-11-28 10:00:33
我知道这个问题特别提到了Angular 6,我只想提一下,从angular 7.1 You can return an UrlTree instead or a boolean起--以及Promise和Observable的等价物-,它将作为一个自动重定向。所以在你的例子中:
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authSer.isAuthenticated().pipe(
map((response) => {
console.log('I ma here');
if (response.status === 200) {
return true;
} else {
console.log('Error getting data');
return false;
}
}),
catchError((error) => of(false)),
map(responseOk => {
// Isolate dealing with true/false results since they can come from different opperators
if (!responseOk) {
return this.router.createUrlTree(['path', 'to', 'redirect'])
}
// alternatively, return a different UrlTree if you feel like it would be a good idea
return responseOk
})
);
}我也强烈建议使用他们的Guide升级到Angular 7。这是非常容易的,它将使你有新的功能,以及带来一堆错误修复。
发布于 2018-11-28 14:37:42
这里示例使用重定向到url来保护。这可能会有帮助:
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthenticationService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isAuth) {
return true;
}
else {
this.router.navigate([state.url]); // or some other url
}
}}https://stackoverflow.com/questions/53508256
复制相似问题