Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnInit not being called after router.navigate

My Angular app is all of a sudden not calling ngOnInit() after router.navigation() which means my components do not load correctly. I thought it may have been due to some changes I made but reverting the changes did not resolve the issue.

Example where normal navigation causes component not to load correctly; This page is navigated to by the following code listing: this.router.navigate(['/result', this.params.data._id]);:

Component not loaded correctly

Reloading the page, the component is loaded correctly:

Component loaded correctly

Here are some of my code listings,

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', component: SampleGridApplicationComponent },
      { path: 'assetitems', component: AssetGridApplicationComponent },
      { path: 'result/:id', component: ResultComponent}

    ]
  },
  { path: 'login', component: LoginComponent, canActivate: [AuthGuard] },
  { path: 'logout', component: LogoutComponent },
  { path: 'signup', component: SignupComponent, canActivate: [AuthGuard] },
  { path: 'reset', component: ResetPasswordComponent, canActivate: [AuthGuard] }
];
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes, {useHash: true})
  ],
  exports: [
    RouterModule
  ],
  providers: [
    AuthGuard,
    NoAuthGuard
  ]
})
export class AppRoutingModule {}

EDIT After some more digging I believe the issue is related to the issue here however the suggested fix does not resolve this issue.

like image 400
Mika571 Avatar asked Jun 25 '17 10:06

Mika571


People also ask

How do I call ngOnInit again?

ngOnInit() is called once for every method. There is no way to make it being called multiple times.

Is ngOnDestroy called on route change?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.

What does router navigate do?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.

What is route reuse strategy?

BaseRouteReuseStrategylink This base route reuse strategy only reuses routes when the matched router configs are identical. This prevents components from being destroyed and recreated when just the fragment or query parameters change (that is, the existing component is reused).


2 Answers

It seems this problem is still around, even after 5.0 has been released, at least the issue https://github.com/angular/angular/issues/18254 is not yet resolved. The good news is that there is a workaround described in the issue, using:

        this.zone.run(() => {
          this.router.navigateByUrl( url );
        });

I had the problem in the onAuthStateChanged callback for Firebase, and the above workaround helped.

like image 119
Mattias Avatar answered Sep 17 '22 17:09

Mattias


The problem ended up being a bug in angular router, downgrading to version 4.1.3 fixed the issue. Hopefully this helps anyone else that tries using the latest version of angular with the Kinvey SDK.

like image 29
Mika571 Avatar answered Sep 20 '22 17:09

Mika571