小编Dav*_*e V的帖子

Angular 2 RC4 Route Guards服务注入

我在Angular 2中遇到了Route Guards的问题.看起来Guard正在获取我的身份验证服务的单独实例.

我试图像Angular文档一样设置我的警卫:

守卫:

@Injectable()
export class AuthenticationGuard implements CanActivate {
    constructor(private router:Router,
            private authenticationService:AuthenticationService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (this.authenticationService.isLoggedIn) {
            return true;
        }

        this.router.navigate(['/login']);
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

服务:

@Injectable()
export class AuthenticationService {
    isLoggedIn:boolean = false;

    login() {
        return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
    }

    logout() {
        this.isLoggedIn = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

登录:

export class LoginComponent {
    constructor(private router:Router,
                private authenticationService:AuthenticationService) {
    }

    login() {
        //TODO: Flesh out actual authentication
        this.authenticationService.login()
            .subscribe(() => …
Run Code Online (Sandbox Code Playgroud)

routes angular

3
推荐指数
1
解决办法
953
查看次数

标签 统计

angular ×1

routes ×1