簡體   English   中英

無需導航即可更改路由器 URL,但會添加到瀏覽器歷史記錄

[英]Change router URL without navigating, but add to browser history

我有一個搜索頁面,用戶可以在其中執行搜索並查看結果。

最初,我的問題是在不導航的情況下更新路由器 URL,但我通過使用“位置”解決了這個問題。

我的 ngOnInit - 我的搜索頁面可以被另一個頁面導航到,所以我會監聽 queryParams 以在發生任何情況時執行搜索:

ngOnInit() {    
    this.queryParamsSubscription = this.activatedRoute.queryParams.subscribe(queryParams => {
      this.searchText = queryParams[TD_QUERY_PARAMS.text];
      if (this.searchText) {
        this.search();
      }
    });
  }

我的搜索方法:

search() {    
    const queryParams: Params = { text: this.searchText };
    const desiredUrl = this.router.createUrlTree([], {
      queryParams: queryParams,
      relativeTo: this.activatedRoute,
      skipLocationChange: true
    });
    this.location.replaceState(desiredUrl.toString());
  }

此實現確保我在用戶在搜索頁面中搜索時更新 URL,這是我的解決方案的第一部分。

但是,我還想在瀏覽器歷史記錄中添加任何搜索,即:

  • 我首先在“localhost:4200/landing”上啟動我的應用程序。

  • 在此頁面上,我有一個搜索欄,觸發時將導航到我的搜索頁面。

  • 在登陸頁面,我搜索“1”。 然后路由器導航到:'localhost:4200/search?text=1'

  • 然后在搜索頁面上,我搜索“2”。 執行搜索,並將 URL 更新為:'localhost:4200/search?text=2'

  • 最后我搜索'3':''localhost:4200/search?text=3'。

當我按下瀏覽器的“返回”按鈕時,我希望導航到“localhost:4200/search?text=2”。

但是,我在頁面中所做的搜索都沒有添加到歷史記錄中,所以我將被導航到我在搜索頁面之前訪問的任何頁面。 就我而言,'localhost:4200/landing'。

如何將這些搜索中的每一個添加到瀏覽器歷史記錄中?

我相信其中之一就是你所需要的:

  1. this.router.navigate(['/yourRouteGoesHere'], { replaceUrl: true });

  2. 您可以使用的其他選項是: SkipLocationChange this.router.navigateByUrl(['yourFullPath'], { skipLocationChange: true });

  3. 使用this.router.replaceUrl('path')

這樣您就可以導航,而無需將此路線添加到歷史記錄中。

這是一個過度思考我面臨的問題的案例。

只需使用router.navigate(['/search'], { queryParams: queryPrams })

我得到了我想要的結果。 URL 已更改,瀏覽器歷史記錄中添加了一個點。

我沒有意識到的是,當僅更改 queryParams 時,router.navigate 不會重新加載整個頁面。

希望這可以幫助任何在同一問題上掙扎的人。

暫無
暫無

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

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