我已经包装了几个组件的ngInit,并检查用户是否登录:
export class ComponentX implements OnInit {
constructor(private _authService: AuthService) {}
ngOnInit() {
if(this._authService.isLoggedIn()) {
// Do stuff
}
else {
// Redirect to loggin page
}
}
}由于我真的不想重复我自己,我想把这个,如果检查到其他地方,将应用到我想要它的组件。
我怎么能这么做?
发布于 2016-10-24 12:38:42
正如居恩特所说的
import { Injectable } from '@angular/core'
import { Router, CanActivate } from '@angular/router'
import { AuthUtils } from "./authUtils.service"
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router, private _authUtils: AuthUtils) {}
canActivate(): boolean {
if(this._authUtils.isLogged()) {
return true
}
else {
this._router.navigate(["/login"])
return false
}
}
}https://stackoverflow.com/questions/40217341
复制相似问题