【问题标题】:Binding URL Params via RouterLink in Angular App在 Angular 应用程序中通过 RouterLink 绑定 URL 参数
【发布时间】:2018-03-13 19:23:34
【问题描述】:

我试图了解加载 routerLink 的基本实现,同时还提取保存的 url 参数会是什么样子。通常,我在应用程序中处理路由的方式是通过订阅可观察对象,如下所示:

private onFilterProcessed(value: any, type: string, body, page)
{
    if (type === 'zip')
    {
        this.processType('addresses.zip', value);
    } if (type === 'location')
    {
        this.processType('addresses.city', value);

    this.filtersService.getByCategory(
        page, this.pagesize, this.body)
        .subscribe(resRecordsData => {
            let data = resRecordsData.data;
        },
        responseRecordsError => this.errorMsg = responseRecordsError);
}

这允许我在 POST 请求中将一些过滤器参数作为正文的一部分传递给 api 调用。这将返回在返回数据之前传入用户过滤器选择的结果。

这一切都按预期工作。当用户“返回”到之前加载的组件时,他们之前的过滤器选择将被传递到 api 调用中,因此“页面”看起来就像他们上次在该页面/组件上时所做的那样。

但是,我的应用程序中还有几个部分是通过 routerLink 加载组件的。它们最初看起来像这样:

<a routerLink="/customer-history" routerLinkActive="selected">Customer History</a>

问题是,既然我在 url 中有过滤器参数,仅此一项是行不通的,因为每次我点击这些特定链接时,它都会清除 url 并仅使用页面标识符重新加载它“客户历史”——因为这就是我目前告诉它要做的事情。

例如,如果用户使用过滤器根据城市过滤结果,则 url 将如下所示:

http://localhost:4200/customer-history;locations=true;locations_place=Seattle

所以问题是,如果他们点击离开,然后通过 routerLink 链接返回到该页面/组件,而不是获取该页面的过滤数据,它将改为加载:

http://localhost:4200/customer-history

所以我的问题是关于如何将这些 url 参数作为 routerLink 的一部分传递。我假设它看起来像这样,带有方括号用于绑定:

<a [routerLink]="['/customer-history', getParams()]" routerLinkActive="selected">Customer History</a>

我不清楚的是如何获取这些特定的 url 参数(只是过滤器参数,而不是组件/页面名称)并通过像这样的绑定传递它们。

我知道 Angular 提供了activatedRoute.snapshot,我可以像这样得到它,传递给getParams()

getParams()
{
    return this.activatedRoute.snapshot;
}

但这将返回完整的 url,而不仅仅是我需要的过滤参数部分。那么我将如何获得我需要的部分网址,并将其传递到此处以附加到网址中的“客户历史记录”? 在基本实现中会是什么样子?

【问题讨论】:

    标签: javascript angular typescript routing routerlink


    【解决方案1】:

    解决此问题的一种方法是在订阅和导航到该页面和所有相关的 url 参数时传递一个解析正确页面/组件的函数,而不是在模板中使用 routerLink。

    为此,我在视图中执行此操作:

    <a (click)="goToCustomerHistory()">Customer History</a>
    

    组件中的那个函数是这样的:

    goToCustomerHistory()
    {
        this.route.params.subscribe(
            (params: any) => {
                this.page = params['page'];
                this.locations = params['locations'];
                this.locations_place = params['locations_place'];
            }
        );
        this.router.navigate(
            ['/customer-history', {
                page: this.page,
                locations = this.locations;
                locations_place = this.locations_place;
            }]);
    }
    

    当然,你还需要在构造函数中引入Router和ActivatedRoute并注入:

    constructor(private router: Router,
                private route: ActivatedRoute){}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 2018-08-30
      • 2021-06-21
      • 2016-11-15
      • 1970-01-01
      相关资源
      最近更新 更多