我正在尝试了解加载 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 的一部分传递进来。我假设它看起来像这样,带有用于绑定(bind)的方括号:
<a [routerLink]="['/customer-history', getParams()]" routerLinkActive="selected">Customer History</a>
我不清楚的是如何获取那些特定的 url 参数(只是过滤器参数,而不是组件/页面名称)并通过这样的绑定(bind)将它们传递进来。
我知道 Angular 提供了 activatedRoute.snapshot,我可以这样获取它,以传递给 getParams()
:
getParams()
{
return this.activatedRoute.snapshot;
}
但这将返回完整的 url,而不仅仅是我需要的过滤器参数部分。那么我如何获得我需要的 url 部分,并将其传递到此处以附加到 url 中的“客户历史记录”? 在基本实现中会是什么样子?
最佳答案
解决这个问题的方法是传递一个函数来解析正确的页面/组件,同时订阅并导航到该页面和所有相关的 url 参数,而不是在模板中使用 routerLink。
为此,我在 View 中执行此操作:
<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,并在构造函数中注入(inject):
constructor(private router: Router,
private route: ActivatedRoute){}
关于javascript - 在 Angular App 中通过 RouterLink 绑定(bind) URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46530315/