Home > OS >  Angular: after router.navigate the page shows old info
Angular: after router.navigate the page shows old info

Time:11-09

I have a web app where the user can choose some products to buy. He could interrupts the configuration process restart it after. Now I'm using localStorage to save the info about products, price...

I have a page where there is a table with the user's offers and he can click and continue configuring the products, but I have a problem here.

Imagine you have start a configuration for a product, and then interrupt this. Now you go to the table page (the page with all the offers ) and when you click on the button to resume another configuration for another product and the sytesm make calls to rebuild the product's info, once all the calls have been made I save info in the localStorage and I use this.router.navigate ([/destination)]

Now in the page where I arrive I have:

constructor(){
    this.offer = JSON.parse(localStorage.getItem("OFFER"));
}

ngOnInit() {
    this.offer = JSON.parse(localStorage.getItem("OFFER"));
    // I have tried to put the localStorage.getItem also in the constructor.
}

Now if I check my localstorage I have the info about right product, but the page where I arrive show the info of the old one. To fix this problem i need to refresh the page.

Now the problem is that I don't want to refresh the page to show the right info, how can I do, when I arrive in the page to show the right information about product without reload the page?

CodePudding user response:

You can do that which mean very time link click it refresh but not probably good for every click.

RouterModule.forRoot(appRoutes, {
  // ..
  onSameUrlNavigation: 'reload',
  // ..
})

You can add router to construction and subscriber to reload data Like

constructor(private router: Router) {
    this.router.events.subscribe(() => {
    this.offer = JSON.parse(localStorage.getItem("OFFER"));
    });
}

I was wrong here should work

constructor(private _route: ActivatedRoute){
    this._route.url.subscribe(url => {
        // Your action/function will go here
    });
}

CodePudding user response:

I am pretty sure that you are trying to navigate to the same route (this.router.navigate (['/destination')]) as you are currently on. Therefore your component will probably not get destroyed and reinstantiated.

This means that your constructor and ngOnInit calls will not be called at all (only after page reload).

You can try setting RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'}) in your RouterModule import, since by default routing to the same URL is ignored (see here: https://angular.io/api/router/RouterConfigOptions#onSameUrlNavigation).

This will result in a reload of the component and constructor and ngOnInit being called.

  • Related