Angular: After switching pages through routing, ngOnInit() will not be triggered.

describe:

I am using the angular 9 version, and there is a problem: when I enter the page through routing, ngOnInit will be executed, switch to other pages and then switch back. At this time, the ngInit of this page will not be actively executed.

reason:

In Angular, when a component is created, its lifecycle methods  ngOnInit() are automatically executed once when the component is initialized. However, when you switch to other pages through routing navigation and then switch back to the original component page, ngOnInit() the method will not be actively executed again.

This is because during route navigation, Angular's router will reuse already created component instances by default instead of destroying and re-creating them. Therefore, ngOnInit() the method will only be called once when the component is first created.

If you want to perform certain actions every time you switch back to the component page, consider using Angular's  ActivatedRoute and  Router to listen for routing events and trigger the corresponding processing logic.

Here's a sample code that shows how to proactively execute some code every time the route switches back to the component:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';

@Component({
  ...
})
export class YourComponent implements OnInit {
  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit(): void {
    // 监听路由导航事件
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        // 检查当前路由是否与要执行代码的组件匹配
        if (this.route.snapshot.routeConfig.path === 'your-route-path') {
          // 执行你想要的操作,比如刷新数据等
          this.yourCustomFunction();
        }
      }
    });
  }

  yourCustomFunction(): void {
    // 在这里编写你想要执行的代码
    console.log('ngOnInit is called every time the route is navigated to');
  }
}

In the above example, we used  Router the  NavigationEnd event to listen for route navigation events. We then check if the current routing path matches the component's path and call the custom method if it matches  yourCustomFunction().

Please note that in the above code  'your-route-path' should be replaced with your actual routing path to match the component where the code will be executed.

Personal solution:

Put the function to be executed under other hook functions, such as ngAfterViewInit()

During the navigation process, Angular's router will reuse already created component instances by default instead of destroying and re-creating them. Is it possible to control the destruction of the previous instance after switching routes?

In Angular, routers by default reuse already created component instances instead of destroying and recreating them. This is to improve performance and reduce resource overhead.

However, if you wish to destroy the previous component instance after switching routes, you can use some options provided by the router to control the destruction and re-creation behavior of the component.

runGuardsAndResolvers One way is to set the option  in the routing configuration file  always. This will force the previous component instance to be destroyed and a new one recreated on each navigation.

const routes: Routes = [
  {
    path: 'example',
    component: ExampleComponent,
    runGuardsAndResolvers: 'always'
  }
];

Another approach is to use  RouteReuseStrategy interfaces to customize the router's reuse policy. You can implement your own  RouteReuseStrategy class and define in it when to reuse component instances and when to destroy them.

Here's a simple example:

import { RouteReuseStrategy, DetachedRouteHandle } from '@angular/router';

export class CustomRouteReuseStrategy implements RouteReuseStrategy {
  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return false;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {}

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return false;
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    return null;
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return false;
  }
}

Then, provide the custom one in your module  RouteReuseStrategy:

import { RouteReuseStrategy } from '@angular/router';
import { CustomRouteReuseStrategy } from './custom-route-reuse-strategy';

@NgModule({
  providers: [
    { provide: RouteReuseStrategy, useClass: CustomRouteReuseStrategy }
  ]
})
export class AppModule { }

Supongo que te gusta

Origin blog.csdn.net/dongnihao/article/details/133277372
Recomendado
Clasificación