I need to take the values from a json which returns true or false based on the user type. I debugged and the true and false values are correct, but despite this the urls of the pages don't open. What am I doing wrong?
auth.guard.ts
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> {
return new Promise((resolve, reject) => {
let flagErrors: boolean;
let flagLabels: boolean;
this.userService.getProfili().subscribe(response => {
for (var i = 0; i < response.result.length; i ) {
const id = response.result[i].id;
if (this.authService.id == id) {
flagErrors = response.result[i].flagErrors;
flagLabels= response.result[i].flagLabels;
break;
}
}
if (flagErrors) {
this.router.navigateByUrl('/errors');
return flagErrors
}
if (flagLabels) {
this.router.navigateByUrl('/label');
return flagLabels
}
});
});
}
app-routing.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'label', component: LabelsComponent, canActivate: [AuthGuard] },
{ path: 'errors', component: ErrorsComponent, canActivate: [AuthGuard] },
];
CodePudding user response:
U must return values from result, so i use boolean observable ... u must add map from rxjs.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.userService.getProfili().pipe(map((res) => {
for (var i = 0; i < res.result.length; i ) {
const id = res.result[i].id;
if (this.authService.id == id) {
flagErrors = res.result[i].flagErrors;
flagLabels= res.result[i].flagLabels;
break;
}
}
if (flagErrors && state.url == 'errors') {
return true
}
if (flagLabels && state.url == 'label') {
return true
}
return false
})
}
CodePudding user response:
The code inside the canActivate
method is not returning the expected value for the guard, which is either a boolean
value or a UrlTree
object.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.userService.getProfili().pipe(map((response) => {
for (let i = 0; i < response.result.length; i ) {
const userId = response.result[i].id;
if (this.authService.id == userId) {
flagErrors = response.result[i].flagErrors;
flagLabels= response.result[i].flagLabels;
break;
}
}
if (flagErrors && state.url == 'errors') {
return this.router.createUrlTree(['/errors'])
}
if (flagLabels && state.url == 'label') {
return this.router.createUrlTree(['/label'])
}
return false
})
app-routing.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'label', component: LabelsComponent, canActivate: [AuthGuard] },
{ path: 'errors', component: ErrorsComponent, canActivate: [AuthGuard] },
];
I don't see a point of using Promise
here only if you need to load it and if so make sure to use resolve()
method.