【问题标题】:Angular 2: How to change activated route URL with replaceStateAngular 2:如何使用 replaceState 更改激活的路由 URL
【发布时间】:2018-05-05 22:25:06
【问题描述】:

在使用replaceState 时,我遇到了一些与激活路由相关的问题。我想要做的是,在提交form 后,我将路由 URL 中的keyIdid 替换为我得到的响应。

让我在这里解释一下。下面是我激活的路由 URL:

home/screen/user/detail/keyId/id

我在此视图下有表单,我使用以下方法提交表单:

onSubmit(userItem: UserItem){ 
     this.userService.saveUser(userItem).subscribe(res => {
     let keyId = res.keyId;
     let id = res.id;

     // tried this but doesn't work
     /* this.router.navigate(["home/screen/user/detail/" + keyId + "/" + id], { replaceUrl: true }) */

     // this one working but seems like temporary fix
     this.location.replaceState("home/screen/user/detail/" + keyId + "/" + id);
   })
  }

上面的代码用新的keyIdid 替换路由URL,但是如果我刷新页面,它会给出一个错误,比如无法匹配任何路由。但我的要求是,一旦我刷新页面,它应该加载更改后的 URL。

我尝试了router.navigate 而不是replaceState,但它没有按预期工作。如果有人可以在这种情况下帮助我,我将非常感激。

【问题讨论】:

    标签: angular routes angular-ui-router


    【解决方案1】:

    也适用于 Angular 2+(即 Angular 9

    你试过了吗?

    import { Location } from '@angular/common';
    
    constructor(private location: Location) { }
    
    this.location.replaceState('/your-url/blah/blah');
    

    以上内容摘自以下example

    希望这可以帮助某人:)

    谢谢

    【讨论】:

      【解决方案2】:

      您可以使用以下代码来完成这项工作:

       this._router.navigate(['YourUrl/UpdatedKeyId/id']);
       window.location.reload();
      

      【讨论】:

        猜你喜欢
        • 2017-01-13
        • 2016-08-31
        • 1970-01-01
        • 1970-01-01
        • 2018-09-09
        • 1970-01-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        相关资源
        最近更新 更多