0
我使用的登錄Auth0
和angular2-jwt
,我試圖實現CanActivate當用戶登錄到塊路由。
我已經實現了登錄密碼進入navbar.component ,並試圖找出如何使其更加模塊化。我有一些服務的例子,但沒有一個與這種情況相匹配,所以這就是我來到這裏的原因。Angular2劃分組件投入服務,並添加AuthGuard
因此,我認爲有兩個步驟進行:
- 實施AuthGuard阻止路線。
- 將此組件分解爲一個服務,以便它可以向AuthGuard發送指令以阻止或允許路由,具體取決於用戶是否登錄。
我希望有人會給我一個解決方案,我可以從中學習。 謝謝。
Navbar.component.ts:
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES, CanActivate } from '@angular/router';
import {tokenNotExpired, JwtHelper} from 'angular2-jwt';
declare var Auth0Lock;
@Component({
moduleId: module.id,
selector: 'navbar',
template : `
<button *ngIf="!loggedIn()" (click)="login()">Login</button>
<button *ngIf="loggedIn()" (click)="logout()">Logout</button>
<a *ngIf="loggedIn()" [routerLink]="['/users']">Users</a>
<button *ngIf="!loggedIn()" (click)="login()" class="btn btn-danger">Login</button>
<button *ngIf="loggedIn()" (click)="logout()" class="btn btn-default">Logout</button>
`,
directives: [ROUTER_DIRECTIVES]
})
export class NavbarComponent{
lock = new Auth0Lock('xxxxxxxxxxxxxxxxx','yyyyyyyyyyyyyy')
jwtHelper: JwtHelper = new JwtHelper();
location: Location;
profile : any;
constructor(){
this.profile = JSON.parse(localStorage.getItem('profile'));
}
login(){
var self = this;
this.lock.show((err: string, profile: string, id_token: string) =>{
if (err){
throw new Error(err);
}
localStorage.setItem('profile', JSON.stringify(profile));
localStorage.setItem('id_token', id_token);
self.loggedIn();
});
}
logout(){
localStorage.removeItem('profile');
localStorage.removeItem('id_token');
this.loggedIn();
}
loggedIn(){
return tokenNotExpired();
}
}
auth.guard.ts:
import { CanActivate } from '@angular/router';
export class AuthGuard implements CanActivate {
canActivate() {
return true;
}
}
app.routes.ts
import { provideRouter, RouterConfig } from '@angular/router';
import {UsersComponent} from './users/users.component';
import {AuthGuard} from './navbar/auth.guard';
export const routes: RouterConfig = [
{ path: 'users', component: UsersComponent, canActivate: [AuthGuard] },
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes),
AuthGuard
];