在app.module.ts中定义这些路由
...
{ path: 'mypath', component: MyComponent, canActivate: [RouteGuard] },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', redirectTo: '/home'}
和这个警卫服务
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AngularFire } from 'angularfire2';
import { AngularFireAuth } from 'angularfire2';
@Injectable()
export class RouteGuard implements CanActivate {
private loggedIn: boolean;
constructor ( private af: AngularFire, private auth: AngularFireAuth ) {}
canActivate(): boolean {
this.auth.subscribe(auth => {
if (auth) { this.loggedIn = true; }
else { this.loggedIn = false; }
// this.router.navigate(['/login']); for future implememtation
});
return this.loggedIn;
}
}
从url // mysite / mypath刷新浏览器应用程序转到// mysite而不是// mysite / mypath(并且还跳过默认路径) .
没有在mypath路线上激活任何防护(即: { path: 'mypath', component: MyComponent }
一切都很完美 .
有谁知道这是一个Angular bug吗?我怎么能避免这种行为?
我的开发环境是:
@angular/cli: 1.0.0-rc.1
node: 7.5.0
os: linux x64
@angular/cli: 1.0.0-rc.1
@angular/common: 2.4.9
@angular/compiler: 2.4.9
@angular/compiler-cli: 2.4.9
@angular/core: 2.4.9
@angular/flex-layout: 2.0.0-rc.1
@angular/forms: 2.4.9
@angular/http: 2.4.9
@angular/material: 2.0.0-beta.2
@angular/platform-browser: 2.4.9
@angular/platform-browser-dynamic: 2.4.9
@angular/router: 3.4.9
谢谢你的帮助 .
PS:我试图在Stack Overflow或Github问题上找到答案而没有找到答案 . 我看到了一个类似的问题Angular 2 routing not working on page refresh with Apache,但这不是我的情况 .
3 回答
你可以给路线卫士一个异步的结果:
感谢@Bougarfaoui El houcine和YounesM的建议,这是我的新警卫服务(完全取自这篇文章:Create a Full Angular Authentication System with Firebase
您正在对您的身份验证服务进行异步调用,这意味着
canActivate()
返回this.loggedIn
before 它将其值设置为true或false . 因为每次你采取'mypath'路线时都会调用警卫this.isLoggedin
将被重置为空现在要避免这种行为,你可以使用你的守卫的布尔 outside 并使用该布尔来跟踪你是否登录 .