gpt4 book ai didi

Angular 2 : Route redirect with AuthGuard

转载 作者:太空狗 更新时间:2023-10-29 18:16:42 25 4
gpt4 key购买 nike

我有一个 Angular2 应用程序,如果用户未登录,它应该阻止到某个页面的路由。这是我的 app.routes 文件

export const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: '**', component: LoginComponent },
];

和我的 AuthGuard 文件

@Injectable()
export class AuthGuard implements CanActivate {
response: ResponseInterface;

constructor(private router: Router, private localStorage: LocalStorageService,
private services: MyService) { }
canActivate() {

let token = String(this.localStorage.get('token'));
if (token != null) {
this.services.keepAlive(token).subscribe(
response => this.response = response,
error => alert(error),
() => {
if (this.response.status == 'OK') {
console.log("response OK");
return true;
} else {
console.log("response KO");
this.router.navigate(['/login']);
return false;
}
}
)

} else {
this.router.navigate(['/login']);
return false;
}

现在,如果我尝试导航到 http://localhost:4200/#/home path 并且我已经将 token 存储到 localStorage 中,没有任何反应:主页未显示并且导航栏上的路径变为 http://localhost:4200/#/ .怎么了?

最佳答案

canActive方法应返回 Observable<boolean> , Promise<boolean>boolean .

您正在订阅 this.services.keepAlive可观察并返回 boolean订阅回调的值,而不是将其返回给 canActivate方法。更改您的代码如下:

canActivate(): Observable<boolean> | Promise<boolean> | boolean {
let token = String(this.localStorage.get('token'));
if (token != null) {
return this.services.keepAlive(token)
.map(response => {
if (response.status == 'OK') {
console.log("response OK");
return true;
} else {
console.log("response KO");
this.router.navigate(['login']);
return false;
}
});
} else {
this.router.navigate(['login']);
return false;
}
}

这样, bool 类型的 Observable ( Observable<boolean> ) 将返回给 canActive方法和路由解析应该按预期工作。

关于 Angular 2 : Route redirect with AuthGuard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41826915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com