簡體   English   中英

Angular2,如何清除路由器導航上的 URL 查詢參數

[英]Angular2, how to clear URL query params on router navigate

我在 Angular 2.4.2 的導航期間努力清除 URL 參數。 我已嘗試附加每個選項以清除以下導航行中的參數,或其中與導航或導航的任何混合,或navigateByUrl,但無法弄清楚如何完成。

this.router.navigateByUrl(this.router.url, { queryParams: {}, preserveQueryParams: false });

舉個例子,我在路由/section1/page1?key1=abc&key2=def並希望保持在同一路由但刪除所有 url 參數,所以最終結果應該是/section/page1

正如 DeborahK 指出的那樣,當我導航到 this.router.url 時,該 URL 已經嵌入了 url 參數。 為了解決這個問題,我將 URL 中的參數作為字符串剝離,然后使用 navigateByUrl 跳轉到那里。

let url: string = this.router.url.substring(0, this.router.url.indexOf("?"));
this.router.navigateByUrl(url);

如果您向它傳遞一個沒有查詢參數的 URL,則使用navigateByUrl將丟棄查詢參數。

或者你可以試試:

this.router.navigate(this.router.url, { queryParams: {}});

注意: navigate而不是navigateByUrl

那樣有用嗎?

如果您不想重新加載頁面,也可以使用Location

import { Location } from '@angular/common';
[...]
this.location.replaceState(this.location.path().split('?')[0], '');

this.location.path()為您提供當前路徑。 您可以通過使用?之前的 URL 中的所有內容重置頁面路徑來刪除參數? .

您可以在導航附加功能中添加replaceUrl: true 這樣,路由器將導航到同一頁面,但您仍然保持在歷史記錄中的相同狀態,並且 url 參數消失了,同時仍然允許您返回到之前的路由。

從文檔:

在替換歷史記錄中的當前狀態時進行導航。

this.router.navigate([], { replaceUrl: true});

使用 skipLocationChange 選項,它不會顯示參數:假設您的網址是

http://本地主機/視圖

現在您的代碼中的某些內容將查詢參數設置為

?q=all&viewtype=total

如果沒有skipLocationChange,您在瀏覽器中的網址(調用導航后)將是:

http://localhost/view?q=all&viewtype=total

使用 skipLocationChange : true 它仍然存在

http://本地主機/視圖

let qp = { q : "all" , viewtype : "total" } 
this.router.navigate(['/view'], {  queryParams: qp,skipLocationChange: true });

從 angular 7.2 開始,您可以使用 state

發送

this.router.navigate(['routename'], { state: { param1: 'bar' } });

接收

let paramobj = history.state;
console.log(paramobj.param1);

通過這種方式,您甚至可以從模板發送大型復雜對象。

這是一個簡單的

this.router.navigate([], {});

// 或者

this.router.navigate([], {
  queryParams: {
   param1:'',
   param2:''
  }
 });

這將清除沒有硬編碼的 URL,並且不會重新加載頁面。

constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router
    )
...
     this.router.navigate([], {
                relativeTo: this.activatedRoute,
                queryParams: {},
                replaceUrl: true,
            });

暫無
暫無

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

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