我有一個Angular2應用程序,應該阻止路由到某個頁面,如果用戶沒有登錄這是我app.routes文件Angular2:路由重定向與AuthGuard
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條路,我已經存儲到localStorage的一個道理,沒有發生:主頁不顯示和導航欄上的路徑變得http://localhost:4200/#/。 有什麼問題?
那麼你看到日誌中的「響應OK」? – echonax
是的,迴應是OK – giozh
沒有我的意思是你有'console.log(「response OK」);'在你的代碼中。你是否在控制檯日誌中看到它? – echonax