当我以用户身份登录并以管理员身份登录时,我希望Web应用程序中具有不同的页面。我做了一个authservice,我从用户对象中获取了isAdmin的值,并且我也有一种方法可以从auth.service.ts中获取...我应该在login.component.ts中添加什么以采用isAdmin参数?现在在我的控制台中显示:
undefined auth.service.ts:41
[token.value...] auth.service.ts:78
false auth.service.ts:85
true login.component.ts:51
当我以用户和admin身份登录时,似乎并没有等待获取isAdmin值,并且总是进入admin页面。我应该在我的login.component.ts中添加什么?
//auth.service.ts
getIsAuth() {
return this.isAuthenticated;
}
getUserAdmin(){
console.log(this.isAdmin);
return this.isAdmin;
}
// auth.guard.ts
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | Observable<boolean> | Promise<boolean> {
const isAuth = this.authService.getIsAuth();
const isAdmin= this.authService.getUserAdmin();
if (!isAuth) {
this.router.navigate(['observatory/api/login']);
}
else{
if (!isAdmin){
this.router.navigate(['observatory/api/user']);
}
else if (isAdmin){
this.router.navigate(['observatory/api/admin']);
}
}
return isAuth;
}
//login.component.ts
onSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
this.authService.login(this.f.username.value, this.f.password.value);
this.loading = true;
this.isAdmin= this.authService.getUserAdmin();
this.authListenerSubs = this.authService
.getAuthStatusListener()
.subscribe(async isAdmin => {
this.isAdmin= await isAdmin;
console.log(this.isAdmin);
if (!this.isAdmin){
this.router.navigate(['/user']);
}
else{
this.router.navigate(['/admin']);
}
});
//auth.service.ts: fuction-login
login( username: string, password: string) {
var user: User = { username: username, password: password };
this.http
.post<any>("http://localhost:3000/api/auth",user, {observe:'response'})
.subscribe((res) => {
const token = res.headers.get('X-OBSERVATORY-AUTH');
console.log(token);
this.token = token;
if (token!==null) {
this.isAuthenticated = true;
this.userId = res.body._id;
this.isAdmin=res.body.isAdmin;
this.userAdmin=res.body.isAdmin;
console.log(this.userAdmin);
this.username=res.body.username;
this.authStatusListener.next(true);
this.saveAuthData(token, this.userId,this.username, this.isAdmin);
}
});
getUserAdmin(){
console.log(this.userAdmin);
return this.userAdmin;
}
//app-routing.ts
const appRoutes: Routes = [
{ path: 'observatory/api/login', component: LoginComponent},
{ path: 'observatory/api/register', component: RegisterComponent },
{path: 'observatory/api/logout', component:LogoutComponent},
{path: 'observatory/api', component: HomeComponent},
{path: 'observatory/api/user',component:UserComponent},
{path:'observatory/api/admin', component:AdminComponent},
{path:'observatory/api/users', component:UsersComponent,canActivate: [AuthGuard]},
// otherwise redirect to home
{ path: '**', component:NotFoundComponent}
];