Xin chào, tôi đã gặp phải sự cố. Bảo vệ CanActivate của tôi được gọi hai lần, khi tôi cố điều hướng đến trang không được phép vì tôi chưa đăng nhập.Góc 2 CanActivate được gọi hai lần
Tôi có 1 mô đun gốc và được cung cấp dịch vụ bảo vệ CanActivate và các dịch vụ khác.
Cảm ơn bạn trước!
Đây là router của tôi:
const appRoutes: Routes = [
{
path: "",
pathMatch: "full",
redirectTo: "/meal-list",
},
{
path: "login",
component: LoginComponent,
},
{
path: "meal-list",
component: MealListComponent,
canActivate: [AuthActivateGuard],
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
và bảo vệ:
@Injectable()
export class AuthActivateGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {
console.log("guard created");
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {
if (!this.authService.authenticated) {
return this.authService.checkLogged().map(res => {
this.authService.authenticated = true;
return true;
}).catch(()=> {
this.authService.authenticated = false;
this.router.navigate(["login"]);
return Observable.of(false);
});
}
return true;
}
}
Chỉ trong nháy mắt bình thường, có vẻ như có rất nhiều câu lệnh 'return' trong mã của bạn ... – sova