我在HomeComponent中使用了以下CanActivate:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
所以在我的app.routing中:
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/index';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { AuthGuard } from './shared/index';
const appRoutes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
export const routing = RouterModule.forRoot(appRoutes);
这是我用来登录的服务:
@Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
login(username: string, password: string) {
console.log('logging in user');
console.log(username);
return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
.map((response: Response) => {
// login successful if there's a jwt token in the response
const user = response.json();
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
}
我的布局结构如下:
<app-layout-header></app-layout-header>
<app-alert></app-alert>
<router-outlet></router-outlet>
<app-layout-footer></app-layout-footer>
标题是这样的:
<nav class="navbar navbar-light">
<div class="container">
<a class="navbar-brand" routerLink="/">plant-simulator</a>
<!-- Show this for logged out users -->
<ul class="nav navbar-nav pull-xs-right">
<li class="nav-item">
<a class="nav-link"
routerLink="/register"
routerLinkActive="active">
Sign Up
</a>
</li>
</ul>
<!-- Show this for logged in users -->
<ul class="nav navbar-nav pull-xs-right">
<li class="nav-item">
<a class="nav-link"
[routerLink]="['/profile', currentUser.firstName]"
routerLinkActive="active">
{{ currentUser.email }}
</a>
</li>
<li class="nav-item">
<a class="nav-link"
[routerLink]="['/login']">
Logout
</a></li>
</ul>
</div>
</nav>
在这个标题html中,我想使用AuthGuard并显示登录用户,如果他已经登录,否则我想显示SignUp链接!
有什么想法吗?
编辑:根据以下帖子的建议,我的AuthenticationService如下所示:
@Injectable()
export class AuthenticationService {
private isLoggedIn: boolean;
constructor(private http: Http) { }
login(username: string, password: string) {
console.log('logging in user');
console.log(username);
return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
.map((response: Response) => {
// login successful if there's a jwt token in the response
const user = response.json();
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
// set the isLoggedIn boolean value to true, so that we can display this in the header
this.isLoggedIn = true;
}
return user;
});
}
loggedIn() {
return this.isLoggedIn;
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
// set the isLoggedIn boolean value to false, so that we can display this in the header
this.isLoggedIn = false;
}
}
我的HeaderComponent看起来像这样:
@Component({
selector: 'app-layout-header',
templateUrl: './header.component.html'
})
export class HeaderComponent {
constructor(
private authService: AuthenticationService
) {}
isLoggedIn() {
const isLogged = this.authService.loggedIn();
console.log('isLogged = ' + isLogged);
return isLogged;
}
}
我的header.html是这样的:
<!-- Show this for logged out users -->
<ul *ngIf='isLoggedIn() == false'
class="nav navbar-nav pull-xs-right">
<li class="nav-item">
<a class="nav-link"
routerLink="/register"
routerLinkActive="active">
Sign Up
</a>
</li>
</ul>
<!-- Show this for logged in users -->
<ul *ngIf='isLoggedIn() == true'
class="nav navbar-nav pull-xs-right">
<li class="nav-item">
<a class="nav-link"
[routerLink]="['/profile', currentUser.id]"
routerLinkActive="active">
{{ currentUser.firstname }}
</a>
</li>
<li class="nav-item">
<a class="nav-link"
[routerLink]="['/login']">
Logout
</a></li>
</ul>
我的做法是否正确?
答案 0 :(得分:3)
如果用户已登录并使用* ngIf管理DOM,则需要签入authService。
<强>打字稿强>
constructor(private authService: AuthService,....){}
...
get loggedIn(){
return this.authService.loggedIn();
}
<强> HTML 强>
....
<!-- Show this for logged in user -->
<ul *ngIf='isLogged' class="nav navbar-nav pull-xs-right">
<li class="nav-item">
<a class="nav-link"
[routerLink]="['/profile', currentUser.firstName]"
routerLinkActive="active">
{{ currentUser.email }}
</a>
</li>
</ul>
<强> AuthService:强>
....
loggedIn() {
//check here if the user is logged by your usual way
// and return true if logged or false, if not
//something like
return this.localStorageService.getData('user') && tokenNotExpired('id_token');
}
您还可以在authService中添加方法,以获取用户名,用户名等。
getProfile() {
//access to API to get info
}