【问题标题】:Angular router. How to navigate to current URL but with different parameters?角路由器。如何导航到当前 URL 但使用不同的参数?
【发布时间】:2018-06-19 22:27:32
【问题描述】:

我有一个 Angular 5 项目,用户在单击项目时导航到这样的路线。

my_domain/{account_id}/item/{item_id}/open/
my_domain/{account_id}/item/{item_id}/closed/
my_domain/{account_id}/item/{item_id}/snoozed/

用户应该能够更改 account_id 或 item_id。所以我希望能够重新加载页面,只更改参数(id)。我怎样才能做到这一点?

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: javascript angular typescript url-routing


【解决方案1】:

角度 8

.component.ts
您可以使用当前 url 并放置参数来导航数组

this.router.navigate([this.router.url, 'open']);

或在 .component.html
您可以将点用作 url "./youparam" 的一部分 - 在本例中为 "./" == current url

< a [routerLink]="['./open']">open</a>

【讨论】:

    【解决方案2】:

    简单:

    import { Router } from '@angular/router';
    ...
    export class YourComponent{
      constructor(public router: Router) {
    
      }
      ...
      myRouteMethod(accountId, itemId, endpointUrl){
        // Use String literals
        this.router.navigate([`/${accountId}/item/${itemId}/${endpointUrl}/`]);
      }
    }
    

    在您的 HTML 中,您可以:

    <div class="wrap">
    <div (click)="myRouteMethod(accountIdSomehow, itemIdSomeHow, 'open')">
    open </div>
    <div (click)="myRouteMethod(accountIdSomehow, itemIdSomeHow, 'close')"> close </div>
    <div (click)="myRouteMethod(accountIdSomehow, itemIdSomeHow, 'other')"> other </div>
    </div>
    

    了解如何获取 accountId 和 itemId 会很有用。 可重用函数会有所帮助,始终考虑参数而不是重复,诀窍是调整模板以与组件动态协作。

    【讨论】:

    • 是的,但问题是我必须这样做三遍(关闭、打盹和打开),但我不想这样做。我需要一种方法,使其适用于任何可能的 URL。
    • 也许您可以添加当前设置这些网址的方式,以便更深入地了解您的预期目的。您可以添加一个附加参数(accountId, itemId, endpoint) 并将导航修改为:.navigate([/${accountId}/item/${itemId}/${endpoint}/])
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 2021-07-12
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多