How to reload an Angularcomponent when I navigate to the same route?

Asked

Viewed 110 times

-1

I’m doing a school project, and in it I have a navbar that has several buttons with routerLinks at the angle, when I click on them, they take me to a route with the path: 'busca/:type/:id'. When this route is accessed I use ngOnInit of the component to make a request for my API through an Angularservice. But when I click on another button of my navbar that leads to the same route, however with the /:id diferente, it does not search because the component is already loaded and ngOnInit is not fired. I’ve tried the following solution, it didn’t work (or I didn’t know how to perform correctly):

Inform onSameUrlNavigation: 'Reload' in router module configuration

@NgModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
 exports: [RouterModule],
})

Inform runGuardsAndResolvers: 'paramsChange' in route configuration.

Use the navigationEnd event in the class

export class SearchComponent implements OnInit {
  constructor(
    private router: Router,
  ) {
    this.router.events.subscribe((e: any) => {
      if (e instanceof NavigationEnd) {
        this.getAll();
      }
    });
  }

  getAll(): void {
    // Busca na api
  }
}
  • It looks really hard to understand!

1 answer

0

Instead of subscribing to the navigation events of the router, you can subscribe to get the modifications of the URL parameters.

In ngOnInit, you can, for example, do it this way:

constructor(private activatedRoute: ActivatedRoute) { }

ngOnInit(): void {
  this.activatedRoute.paramMap.subscribe(paramsMap => {
    console.log(`Parâmetro da URL: ${paramsMap.get('id')}`);

    // Faz a consulta na tua API aqui!
    // this.fetchData();
  });
}

Whenever route parameters are modified, you will be notified.

I set an example at Stackblitz demonstrating this behavior. Note in the console that you will log in the parameters whenever they are changed.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.