问题描述
我想使用守卫来决定用户是否可以导航到登录页面,但我知道我的逻辑是错误的,因为 Promise
。
请参阅下面的代码。
canActivate(): boolean | Observable<boolean> | Promise<boolean> {
if (!this.localStorage.getobject('isInitialized')) {
this.router.navigate(['/locaties']);
return true;
}
return false;
}
我知道我在做什么是错误的,但我缺乏有关解决此问题的承诺的知识。我需要做什么才能完成这项工作?
这是我的localstorage.getobject()
:
// Returns object
async getobject(key: string) {
const ret = await Storage.get({ key: key });
return JSON.parse(ret.value);
}
解决方法
如果你想在你的 can activate 方法中使用基于异步结果的条件,那么你可以使用 Promise。如果您打算使用本地存储中的直接值,则无需使用 promise。您可以执行以下操作以使用 promise...
canActivate(): boolean | Observable<boolean> | Promise<boolean> {
return new Promise(() => {
if (!this.localStorage.getObject('isInitialized')) {
this.router.navigate(['/locaties']);
// Do not allow the route
resolve(false);
} else {
// Allow the route
resolve(true);
}
});
}
,
所以这里有一些问题,但我认为承诺不是其中之一。您的函数签名表示您可以选择返回三种类型之一,
canActivate(): boolean | Observable<boolean> | Promise<boolean>
但你只返回一个布尔值,所以你真的可以重写这个,
canActivate(): boolean
但这不是问题。如果没有看到您的路线设置,很难说,但是如果他们请求的路线被允许并且没有必要,您似乎正在重新路由用户。当用户已经尝试导航到一个页面时,路由守卫会运行。如果路由保护返回 true,则允许进行该导航,并且用户将继续到路由保护所保护的任何页面。
但是当路由保护返回 false 时,您应该指定重定向页面。换句话说,当用户无法访问守卫后面的页面时,您想将它们发送到哪里?
一般来说,这看起来像这样,
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(state: RouterStateSnapshot): boolean {
if (!this.localStorage.getObject('isInitialized')) {
//No need to route here,user will be taken to the route they were trying access
return true;
} else {
//Send the user back to the '/anotherpage' path if they are not logged in
this.router.navigate(['/anotherpage']);
return false;
}
}
}
然后在这样的地方定义你的路线,
export const appRoutes: Routes = [
{
path: 'pageProtectedByAuthGuard',component: YourComponent,canActivate: [AuthGuard]
}
];
然后在你的模块中你需要导入这些路由,
@NgModule({
imports: [RouterModule.forRoot(appRoutes,{ enableTracing: false })],...
})
关于 CanActivate 的更多信息:https://angular.io/api/router/CanActivate
,答案是
this.localStorage.getObject('isInitialized').then((res) => {
if (res == true) {
this.router.navigate(['/locaties']);
return false;
}
});
return true;
}
必须记住,当用户想要导航到页面时,auth 守卫会被触发。没有必要让它变得更复杂