首页 文章

在Angular App中通过RouterLink绑定URL参数

提问于
浏览
2

我试图了解加载routerLink的基本实现是什么,同时还拉入保存的url params看起来像 . 通常,我在我的应用程序中处理路由的方式是通过订阅一个observable,看起来像这样:

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);
}

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

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

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

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

问题是,现在我在网址中有过滤器参数,仅此一项不起作用,因为每次点击这些特定链接时,它都会清除网址,并仅使用页面标识符“客户 - 重新加载它历史“ - 因为这就是我目前正在告诉它的事情 .

例如,如果用户使用过滤器来过滤基于城市的结果,则网址将如下所示:

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

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

http://localhost:4200/customer-history

所以我的问题是如何将这些url params作为routerLink的一部分传递 . 我假设它看起来像这样,用方括号进行绑定:

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

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

我知道Angular使activateRoute.snapshot(我可以这样得到)传入 getParams()

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

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

1 回答

  • 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){}
    

相关问题