在 Angular 4/5 和 TypeScript 中重新加载同一页面

Reloading same page in Angular 4/5 & TypeScript

我正在借助路由开发单页应用程序:

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

当我在上面的页面时,我正在使用 REST 调用添加客户。客户更新后,我希望我的页面刷新并重新加载 /customer-home 页面视图。

我的方法如下所示:

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

问题是 location.reload 刷新页面并重定向到主页。

我已经为该位置做了一个控制台日志:

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

有什么办法,我可以使用路由重新加载我的页面和数据,我不想在地址栏中显示 URL。

PS 我已经尝试重定向到其他组件,然后返回到当前组件,但它不会重新加载数据,也不会显示最新添加的客户。

在单页应用程序中使用 Location.reload 与 SPA 的意图相反。

您似乎正在尝试重新加载页面以从您的服务器获取新数据。

加载数据不应该是路由器的工作。您应该在插入后或 postEntity 方法的回调中请求数据,而不是重新加载页面。

不过,与再次请求数据相比,您应该简单地将实体添加到最新添加的客户数组或您用来保存数据的任何对象中。

您可以使用路由器服务 redirect/reload 到您的客户页面,如果您出于某种原因想要这样做的话。

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

但我建议采纳其他人的建议并使用 Observables 或 Promises 来重新加载您的数据而不是整个页面。 Observable 应该看起来像下面提供的那样,我建议在更新后让您的 Post 方法 return 客户。

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