【问题标题】:Reloading same page in Angular 4/5 & TypeScript在 Angular 4/5 和 TypeScript 中重新加载同一页面
【发布时间】:2018-09-10 12:52:09
【问题描述】:

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

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

【问题讨论】:

  • 可能是因为skipLocationChange: true导航历史没有看到路线变化。你为什么这样做?你为什么要重新加载页面?
  • 确实如此。为了获得最新的更改,我正在这样做。我现在在 cmets 中得到了一个解决方案,可以在 post 上得到一个 promise 并在当前数组中添加实体。

标签: angular typescript routing routes angular4-router


【解决方案1】:

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

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

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

虽然,比再次请求数据要好,但您应该简单地将实体添加到最新添加的客户数组或用于保存数据的任何东西。

【讨论】:

    【解决方案2】:

    如果您出于某种原因想要这样做,您可以使用路由器服务重定向/重新加载到您的客户页面。

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

    但我建议采纳其他人的建议并使用 Observables 或 Promises 来重新加载您的数据,而不是整个页面。 Observable 应该如下所示,我建议让您的 Post 方法在更新后返回客户。

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

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 2018-08-02
      • 2017-11-22
      • 2020-01-16
      • 2023-03-28
      • 1970-01-01
      • 2023-03-25
      • 2018-10-07
      • 1970-01-01
      相关资源
      最近更新 更多