abhinav3414
abhinav3414

Reputation: 967

Reloading same page in Angular 4/5 & TypeScript

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.

Upvotes: 4

Views: 14851

Answers (2)

Nolan Walker
Nolan Walker

Reputation: 352

You could use the router service to redirect/reload to your customer page if that is what you are looking to do for some reason.

addNewCustomer(customer) {
    this.dataService.postEntity('customers', customer);
    this.router.navigate(['/customer-home']);
}

But I would suggest taking everyone else's suggestions and use Observables or Promises to reload your data instead of the entire page. The Observable should look something like so, provided below and I would suggest having your Post method return the customer after updating it.

addNewCustomer(customer) {
    this.dataService
        .postEntity('customers', customer)
        .subscribe(
            update => this.customer = update;
            err => console.log(err); 
        )
}

Upvotes: 3

Gustavo Lopes
Gustavo Lopes

Reputation: 4174

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.

Upvotes: 3

Related Questions