在我的[[Angular 8应用程序内部,我有这个路由文件:
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
]
})
在我的FirstComponent.ts内部,我执行了此导航操作:
goToSecond(){ this.router.navigate(['FirstComponent/SecondComponent '], {skipLocationChange: true}); }
我的问题是导航似乎无法继续,因为正如我想象的那样,对“”的处理需要一段时间,这就是为什么在丑陋的工作流程中,我已将其更改为以下内容:myModuleGuard
goToSecond(){
setTimeout(() => {
this.router.navigate(['FirstComponent/SecondComponent '], {skipLocationChange: true});
});
}
这使它起作用,但是,这似乎很不礼貌。特别是在我的Angular 8应用程序中,我具有以下路由文件:const myRoutes:Routes = [{路径:”,组件:FirstComponent,canActivate:[RegistrationSrcdGuard]},{路径:'FirstComponent',组件:...] >setTimeout
的使用>[我的守卫看起来像这样:
@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 ; } }
您的主张,使它变得更好??
myTreatment()
方法是一个Observable,您应该在getPermissions()
方法中返回该Observable而不是进行订阅。如下所示修改您的方法: