如果已经登录,我打算重定向用户从打开登录页面重定向。我工作了。但是,我必须根据用户角色重定向到其他页面。
这是工作代码。如果有人打开此页面,它将重定向到/ admin / dashboard。
export class LoginComponent implements OnInit {
public user = {} as {email?: string; password?: string; };
constructor(
private authService: AuthService,
private router: Router
) {
if (this.authService.session.isActive) {
this.router.navigate(['/admin/dashboard']);
}
}
ngOnInit() {
}
login() {
this.authService.login(`${this.user.email}:${this.user.password}`).subscribe(data => {
const token: Token = {token: data.token} as Token;
this.authService.saveToken(token);
this.authService.session.token = token;
this.authService.session.isActive = true;
this.authService.session.profile = data.user as Profile;
this.authService.saveProfile(this.authService.session.profile);
if (data.user.role === 'admin') {
this.router.navigate(['/admin/dashboard']);
} else {
this.router.navigate(['/admin/submissions']);
}
});
}
}
我想根据用户类型进行重定向,因此进行了以下修改,但不起作用:
if (this.authService.session.isActive && data.user.role === 'admin') {
this.router.navigate(['/admin/dashboard']);
} else {
this.router.navigate(['/admin/submissions']);
}
我收到此错误:
ReferenceError: data is not defined
如何解决此问题?
我已经尝试过了:
this.authService.login(`${this.user.email}:${this.user.password}`).subscribe(data => {
if (this.authService.session.isActive && data.user.role === 'admin') {
this.router.navigate(['/admin/dashboard']);
} else {
this.router.navigate(['/admin/submissions']);
}
});
并收到以下响应错误:
Status Code: 400 Bad Request
答案 0 :(得分:1)
if (this.authService.session.isActive && this.authService.session.profile.role === 'admin') {
this.router.navigate(['/admin/dashboard']);
} else {
this.router.navigate(['/admin/submissions']);
}
在ngOnInit()中尝试
登录之前,您将在ngOnInit()中使用一个重定向逻辑。如果会话处于活动状态,这将检查并完成其工作。