我的用户具有不同的访问级别。我有一个通用警卫检查是否设置了令牌并允许访问。但是,我很困惑,因为如何限制用户在访问级别上输入页面。已经进行了一些研究,但对离子4看不到很多。
login.ts
login(emailin, pwin) {
const data = {
email: emailin,
pw: pwin,
};
return this.http.post<any>(apiUrl + 'login.php', JSON.stringify(data))
.pipe(first())
.subscribe((result) => {
this.storage.set('token', result.jwt);
if (result.level === 'Consultant') {
this.router.navigate(['/menu/first/tabs/tab1'], result);
this.authState.next(true);
} else if (result.level === 'Volunteer') {
this.router.navigate(['register'], result);
this.authState.next(true);
} else if (result.level === 'Clinician') {
this.router.navigate(['/menu/first/tabs/tab1']);
this.authState.next(true);
}
},
(error) => {
if (emailin === '' || pwin === '' ) {
this.alertService.presentAlertLogin();
} else if (error.status === 403) {
this.alertService.presentAlertLogin();
} else if (error.status === 401) {}
});
}
isAuthenticated() {
return this.authState.value;
}
Guard.ts
export class Guard implements CanActivate {
path: ActivatedRouteSnapshot[];
route: ActivatedRouteSnapshot;
constructor(public router: Router, public authService: AuthService) { }
// Works but ony if a JWT is present.
canActivate(): boolean {
if (this.authService.isAuthenticated() === false) {
this.router.navigate(['not-found']);
}
return this.authService.isAuthenticated();
}
}
您可以使用多个警卫对于需要特殊访问级别的页面。例如,
顾问页面将有两个警卫,如下
path : 'consult'
canActivate : [ Guard, ConsultGuard ]
临床医生
path : 'clincian'
canActivate : [ Guard, ClinicianGuard ]
和在那些特定的警卫中,您只会检查访问级别,以便为了输入路径,所有警卫都需要返回true
。
因此,您必须保存您的login.php
响应,或者仅保存Auth Service中的访问级别才能使用它。