我的Angular应用程序突然在router.navigation()之后没有调用ngOnInit(),这意味着我的组件无法正确加载.我认为这可能是由于我做出的一些改变,但恢复改变并没有解决问题.
正常导航导致组件无法正确加载的示例;此页面由以下代码列表导航:
this.router.navigate([‘/ result’,this.params.data._id]);:
重新加载页面,组件正确加载:
以下是我的一些代码清单,
app.module.ts
@NgModule({ imports: [ BrowserModule,FormsModule,AppRoutingModule,AgGridModule.withComponents( [SampleResultButtonComponent] ),ChartsModule ],declarations: [ AppComponent,LoginComponent,logoutComponent,SignupComponent,FilesComponent,NavbarComponent,ProfileComponent,UploadComponent,SampleGridApplicationComponent,SampleResultButtonComponent,AssetGridApplicationComponent,ResultComponent,ResetPasswordComponent,AssetComponentDetailComponent ],bootstrap: [ AppComponent ],entryComponents: [AssetComponentDetailComponent] }) export class AppModule {}
APP-routing.module.ts
@Injectable() export class NoAuthGuard implements CanActivate { constructor(private router: Router) {} canActivate() { const activeUser = Kinvey.User.getActiveUser(); if (activeUser) { return true; } // Navigate to the login page this.router.navigate(['/login']); return false; } } @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router) {} canActivate() { const activeUser = Kinvey.User.getActiveUser(); console.log("AuthGuard,CanActivate"); if (!activeUser) { return true; } // Navigate to the main page this.router.navigate(['']); return false; } } const appRoutes: Routes = [ { path: '',component: NavbarComponent,canActivate: [NoAuthGuard],children: [ { path: '',component: SampleGridApplicationComponent },{ path: 'files',component: FilesComponent },{ path: 'upload',component: UploadComponent },{ path: 'profile',component: ProfileComponent },{ path: 'sampleitems',{ path: 'assetitems',component: AssetGridApplicationComponent },{ path: 'result/:id',component: ResultComponent} ] },{ path: 'login',component: LoginComponent,canActivate: [AuthGuard] },{ path: 'logout',component: logoutComponent },{ path: 'signup',component: SignupComponent,{ path: 'reset',component: ResetPasswordComponent,canActivate: [AuthGuard] } ]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes,{useHash: true}) ],exports: [ RouterModule ],providers: [ AuthGuard,NoAuthGuard ] }) export class AppRoutingModule {}
似乎这个问题仍然存在,即使5.0已经发布,至少问题
https://github.com/angular/angular/issues/18254尚未解决.好消息是该问题中描述了一种解决方法,使用:
原文链接:https://www.f2er.com/angularjs/142245.htmlthis.zone.run(() => { this.router.navigateByUrl( url ); });
我在Firebase的onAuthStateChanged回调中遇到了问题,上述解决方法也有帮助.