【发布时间】:2022-01-05 04:34:27
【问题描述】:
我有一个以 ASP.NET Core 作为后端,Angular-13 作为前端的项目。
当用户成功登录后,我在 POSTMAN 上收到了这样的回复:
{
"status_code": 200,
"message": "Successfully Logged In",
"result": {
"token": "gggggffffffffffffdddddddddddd",
"user": {
"id": 3,
"user_name": "smith",
"last_login": "2022-01-03T12:35:26.0305649"
},
"roles": [
"Teacher"
],
}
}
这是 Angular 代码:
user.ts:
export interface IResponse<T> {
message: string;
error: boolean;
code: number;
results: T;
}
export interface IUser {
userName?: string;
lastLogin?: Date;
token?: string;
roles?: string[];
expires?: Date;
}
auth.service.ts:
export class AuthService {
baseUrl = environment.apiUrl;
private currentUserSource = new ReplaySubject<IUser>(1);
currentUser$ = this.currentUserSource.asObservable();
constructor(private http: HttpClient, private router: Router) { }
login(model: any){
return this.http.post(this.baseUrl+'auth/login', model).pipe(
map((res: IUser)=>{
const user = res;
if(user){
this.setCurrentUser(user);
}
})
)
}
setCurrentUser(user: IUser){
if(user){
user.roles = [];
const roles = this.getDecodedToken(user.token).role;//copy token to jwt.io see .role
Array.isArray(roles) ? user.roles = roles : user.roles.push(roles);
localStorage.setItem('user', JSON.stringify(user));
this.currentUserSource.next(user);
}
}
getDecodedToken(token: string) {
return JSON.parse(atob(token.split('.')[1]));
}
}
在 Angular 前端,我有两个仪表板:教师仪表板和学生仪表板
auth.component:
createForm() {
this.loginForm = new FormGroup({
UserName: new FormControl('', Validators.required),
Password: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(80)])
})
}
login(){
this.authService.login(this.loginForm.value).subscribe(res=>{
this.router.navigateByUrl('/');
}, error=>{
this.toastr.error(error.error);
})
}
如果用户成功登录。如果用户的角色是教师,它应该重定向到教师仪表板,如果角色是学生,它应该重定向到学生仪表板。
我如何做到这一点?
谢谢
【问题讨论】: