Home > database >  Angular re-run ngOnInit when coming back to an initialized page
Angular re-run ngOnInit when coming back to an initialized page

Time:10-29

When comming back to an initialized page it doesn't run ngOnInit. For example /user/profile shows username, I go on /user/settings change username, and came back to /user/profile. Username on /user/profile didn't change because ngOnInit wasn't called.

So what I want is to re-init page which has been already initialized. This is router.service.ts which is used for navigation:

export class RouterService {
  constructor(
    private router: Router,
  ) {
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
    this.router.onSameUrlNavigation = "reload";
  };


  async go(path: string[], options: NavigationExtras = {}) {
    this.router.navigate(path, { ...options });
  }
}

If I add replaceUrl: true to the function options it works, initted page re-inits, but the url is not being saved to the browser history and browser back button doesn't work (it redirects to the beggining of the app).

This is app.module.ts:

@NgModule({
    declarations: [AppComponent],
    imports: [
        ...
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
    ],
    providers: [
        { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    ],
    bootstrap: [AppComponent]
})

This is app-routing.module.ts:

@NgModule({
    imports: [
        RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, onSameUrlNavigation: "reload" }),
    ],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Those are the routes:

const routes = [
    {
        path: "user/profile",
        loadChildren: () => import("./user/profile/profile.module").then(m => m.ProfilePageModule),
        canActivate: [LoggedGuard],
    },
    {
        path: 'user/settings',
        loadChildren: () => import('./user/settings/settings.module').then(m => m.SettingsPageModule),
        canActivate: [LoggedGuard],
    },

CodePudding user response:

Lifecycle hooks aren't intended to be called manually. That said, in the main components which you want to re-run the routines, you can subscribe to router events and call whatever functions you wish when the route matches whatever value you wish it to for the given page.

CodePudding user response:

With this method in ionic you are destroying page stacks. You don't need to re-init a page, you can simply use ionic lifecycle hooks instead of angular's. ionViewWillEnter instead of ngOnInit, which is called whenever the page is opened, not when initiated.

  • Related