簡體   English   中英

在 Angular App 中通過 RouterLink 綁定 URL 參數

[英]Binding URL Params via RouterLink in Angular App

我試圖了解加載 routerLink 的基本實現,同時還拉入保存的 url 參數會是什么樣子。 通常,我在應用程序中處理路由的方式是通過訂閱 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);
}

這允許我將一些過濾器參數作為 POST 請求正文的一部分傳遞給 api 調用。 這將返回在返回數據之前傳入用戶過濾器選擇的結果。

這一切都按預期工作。 當用戶“返回”到之前加載的組件時,他們之前的過濾器選擇將被傳遞到 api 調用中,因此“頁面”看起來就像他們上次訪問該頁面/組件時所做的一樣。

但是,我的應用程序中還有幾個部分,我通過 routerLink 加載組件。 他們最初是這樣的:

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

問題是,現在我在 url 中有過濾器參數,僅此一項是行不通的,因為每次我單擊這些特定鏈接時,它都會清除 url 並僅使用頁面標識符“customer-歷史”——因為這就是我目前告訴它要做的。

例如,如果用戶使用過濾器根據城市過濾結果,則 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 提供了可用的 activationRoute.snapshot,我可以這樣獲取,以傳遞給getParams()

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

但這將返回完整的 url,而不僅僅是過濾器參數部分,這是我需要的。 那么我將如何獲取我需要的 url 部分,並將其傳遞到此處以附加到 url 中的“客戶歷史記錄”? 在基本實現中會是什么樣子?

解決此問題的一種方法,而不是在模板中使用 routerLink,是在訂閱和導航到該頁面和所有相關 url 參數時傳遞一個解析正確頁面/組件的函數。

為此,我在視圖中執行此操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM