Reloading same page in Angular 4/5 & TypeScript

abhinav3414 picture abhinav3414 · Mar 31, 2018 · Viewed 13.8k times · Source

I am developing a one page application with the help of routes:

this.router.navigate(['/customer-home'], { skipLocationChange: true });

When I am at the above page, I am adding a customer using a REST call. After the customer gets updated, I want my page to refresh and reload the /customer-home page view.

My method looks like below :

  addNewCustomer(customer) {
    this.dataService.postEntity('customers', customer);
    location.reload();
  }

The problem is that location.reload refreshes the page and redirects to home page.

I have done a console log for the location:

Location {replace: ƒ, assign: ƒ, href: "http://localhost:4200/", ancestorOrigins: DOMStringList, origin: "http://localhost:4200", …}

Is there any way, I can reload my page and data using routes, and I do not want to show the URL in address bar.

PS I have already tried redirecting to some other component and then coming back to current component, but it does not reloads the data and does not shows latest added customer.

Answer

Gustavo Lopes picture Gustavo Lopes · Apr 1, 2018

Using Location.reload in a Single Page Application does the opposite of what a SPA intends to do.

It seems you're trying to reload the page for getting the new data from your server.

Loading the data shouldn't be the Router job. Instead of reloading the page, you should request the data after the insertion or on the callback of your postEntity method.

Although, better than requesting data again, you should simply add the Entity to the latest added customers array or whatever you use to hold the data.