Within my Angular 8 application, the routing file is structured as below:
const myRoutes: Routes = [
{path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]},
{path: 'FirstComponent ',
component: FirstComponent ,
canActivate: [myModuleGuard] ,
children:[
{path: 'SecondComponent ', component: SecondComponent , canActivate: [myModuleGuard]},
]
},
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(myRoutes)
],
declarations: [],
exports: [
RouterModule
]
})
In the FirstComponent.ts file, there is a navigation action defined as:
goToSecond(){
this.router.navigate(['FirstComponent/SecondComponent '], {skipLocationChange: true});
}
The issue arises when navigating, as the processing within "myModuleGuard" seems to cause delays.
To address this, I resorted to an interim solution by modifying it as follows:
goToSecond(){
setTimeout(() => {
this.router.navigate(['FirstComponent/SecondComponent '], {skipLocationChange: true});
});
}
Although functional, this workaround using setTimeout
appears suboptimal.
The MyGuard used in the application is presented below:
@Injectable()
export class MyGuard implements CanActivate {
constructor(private myService: MyService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const result = this.myService.getPermission();
return result ;
}
public getPermission() {
let myResult : boolean
myTreatment().subscribe(
res => {
return myResult = res;
},
err => {}
);
return myResult ;
}
}
Any suggestions for improving this process?