我有一个简单的应用程序,通过Appcomponent加载材料设计Ui。我需要在加载应用程序组件之前对用户进行身份验证。
app组件如下
import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES,CanActivate} from 'angular2/router';
import {AuthHttp,AuthConfig, tokenNotExpired, AUTH_PROVIDERS} from 'angular2-jwt';
import {HomeComponent} from '../home/HomeComponent'
import {AboutComponent} from '../about/AboutComponent'
import {HeaderComponent} from './HeaderComponent'
import {LoginComponent} from '../login/LoginComponent'
import {AuthService} from '../../services/AuthService'
import {SidebarComponent} from './SidebarComponent'
import {DashboardComponent} from './DashboardComponent'
import {MDL} from './MaterialDesignLiteUpgradeElement';
@RouteConfig([
{path: 'app/home', component: HomeComponent, as: 'Home'},
{path: 'app/dashboard', component: DashboardComponent, as: 'Dashboard'},
{path: 'app/about', component: AboutComponent, as: 'About'},
{path: 'app/login', component: LoginComponent, as: 'Login'},
{path: 'app/*', redirectTo: ['Login']} // this redirect is not working for some reason
])
@Component({
selector: 'my-app',
/*template: '<router-outlet></router-outlet>',*/
template: `
<body>
<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header">
<app-header mdl class="demo-header mdl-layout__header mdl-color--grey-100 mdl-color-text--grey-600"></app- header>
<app-sidebar class="demo-drawer mdl-layout__drawer mdl-color--blue-grey-900 mdl-color-text--blue-grey-50">
</app-sidebar>
<main class="mdl-layout__content mdl-color--grey-100">
<router-outlet></router-outlet>
</main>
</div>
<script src="https://code.getmdl.io/1.1.3/material.min.js"></script>
</body>
`,
/*styleUrls: ['../app/assets/styles.css'], */
directives: [ROUTER_DIRECTIVES,SidebarComponent,HeaderComponent,MDL],
providers: [AUTH_PROVIDERS,AuthService]
})
export class AppComponent {
constructor() {}
}
我有一个登录组件,用户登录如下
import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {AuthHttp,AuthConfig, tokenNotExpired, AUTH_PROVIDERS} from 'angular2-jwt';
import {AuthService} from '../../services/AuthService'
@Component({
selector: 'protected',
template: '',
directives: [ROUTER_DIRECTIVES],
providers: [AUTH_PROVIDERS,AuthService]
})
export class LoginComponent {
constructor(private auth: AuthService) {
this.auth.login();
}
login() {
this.auth.login();
}
logout() {
this.auth.logout();
}
static loggedIn() {
return tokenNotExpired();
}
}
登录组件使用AuthService
AuthService
import {Injectable} from 'angular2/core';
import {ROUTER_DIRECTIVES, Router} from "angular2/router";
declare var Auth0Lock: any;
@Injectable()
export class AuthService {
constructor(private router: Router) {}
lock = new Auth0Lock('KEY','URL');
login() {
this.lock.show((error: string, profile: Object, id_token: string) => {
if (error) {
console.log(error);
return false;
}
localStorage.setItem('profile', JSON.stringify(profile));
localStorage.setItem('id_token', id_token);
this.router.navigate(['Home']);
});
}
logout() {
localStorage.removeItem('profile');
localStorage.removeItem('id_token');
}
}
我尝试使用@CanActivate注释AppComponent,如下所示 但这似乎并没有像AppComponent一样加载任何方式。
@CanActivate(() => LoginComponent.loggedIn())
export class AppComponent {
}
如何在没有authnetication的情况下阻止appComponent加载的任何想法?
答案 0 :(得分:2)
如果允许此人导航到该路线,您可以实施自己的RouterOutlet
覆盖acitvate
方法进行检查。
import {Directive, DynamicComponentLoader, ElementRef} from "angular2/core";
import {AuthService} from '../../services/AuthService'
import {Router, RouterOutlet, ComponentInstruction} from "angular2/router";
@Directive({
selector: 'auth-router-outlet'
})
export class AuthRouterOutlet extends RouterOutlet {
private _protectedRoutes = {
'app/home': true,
'app/dashboard': true,
'app/about': true
};
constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, private _router: Router, nameAttr: string, private _authService: AuthService) {
super(_elementRef, _loader, _router, nameAttr);
}
activate(nextInstruction: ComponentInstruction): Promise<any> {
if (this._protectedRoutes[nextInstruction.urlPath]) {
if (!this._authService.loggedIn()) {
this._router.navigate(['Login']);
}
}
return super.activate(nextInstruction);
}
}
在AppComponent
中,只需将<router-outlet></router-outlet>
替换为<auth-router-outlet></auth-router-outlet>
。
对于RouteConfig
中的重定向,请使用两个这样的星号:
@RouteConfig([
{path: 'app/home', component: HomeComponent, as: 'Home'},
{path: 'app/dashboard', component: DashboardComponent, as: 'Dashboard'},
{path: 'app/about', component: AboutComponent, as: 'About'},
{path: 'app/login', component: LoginComponent, as: 'Login'},
{path: 'app/**', redirectTo: ['Login']} // two asterisks here
])