gpt4 book ai didi

javascript - Angular 4 使用 Guard 进行条件显示

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:07 25 4
gpt4 key购买 nike

我在 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>

这里header是这样的:

<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>

在此 header html 中,我想使用 AuthGuard 并显示已登录用户(如果他已登录),否则我想显示注册链接!

有什么想法吗?

编辑:根据下面帖子的建议,我的 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>

我做的对吗?

最佳答案

如果用户已登录并使用 *ngIf 管理 DOM,您将需要 checkin authService。

typescript

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>

授权服务:

....
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
}

关于javascript - Angular 4 使用 Guard 进行条件显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46005867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com