要保护用户详细信息并在Angular应用中实施JWT令牌和NgRx,可以按照以下步骤进行:
添加JWT令牌认证:
创建一个AuthService:
创建一个AuthGuard:
创建一个UserActions:
SaveUser
。SaveUser
action,并更新用户信息的状态。在AppComponent中加载用户信息:
下面是一个简单的代码示例:
auth.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class AuthService {
private apiUrl = 'http://example.com/api/auth';
constructor(private http: HttpClient, private store: Store) {}
login(credentials: any): Observable {
return this.http.post(`${this.apiUrl}/login`, credentials).pipe(
tap((res: any) => {
// 保存用户令牌和其他信息到本地存储
localStorage.setItem('token', res.token);
this.store.dispatch(new SaveUser(res.user));
})
);
}
logout() {
// 删除本地存储的令牌和用户信息
localStorage.removeItem('token');
this.store.dispatch(new SaveUser(null));
}
}
auth.guard.ts:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (!this.authService.isAuthenticated()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
user.actions.ts:
import { Action } from '@ngrx/store';
export const SAVE_USER = '[User] Save User';
export class SaveUser implements Action {
readonly type = SAVE_USER;
constructor(public payload: any) {}
}
export type UserActions = SaveUser;
user.reducer.ts:
import { UserActions, SAVE_USER } from './user.actions';
export interface UserState {
user: any;
}
const initialState: UserState = {
user: null
};
export function userReducer(state = initialState, action: UserActions) {
switch (action.type) {
case SAVE_USER:
return {
...state,
user: action.payload
};
default:
return state;
}
}
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { AuthService } from './auth.service';
@Component({
selector: 'app-root',
template: `
Hello, {{ user.name }}!
`
})
export class AppComponent implements OnInit {
user: any;
constructor(private authService: AuthService, private store: Store) {}
ngOnInit() {
this.store.select('user').subscribe(userState => {
this.user = userState.user;
});
}
}
这是一个简单的示例,用于保护用户详细信息并在