簡體   English   中英

在 URL 中動態存儲查詢參數的最佳方法是什么?

[英]What is the best way to store query paramaters in the URL dynamically?

我有多個搜索字段,我想將查詢參數存儲在 URL 中,但我不知道該怎么做。

組件的路徑如下所示:

const routes: Routes = [
  {path: 'detailedview/:type/:id', component: DetailViewComponent}
];

:type:id是固定值。 在這些值之后,我需要 append 這樣的 url 段q=...&title=...&...長度因填充的字段而異。 然后我需要以某種方式獲取數據。

你認為我應該在我的路徑中添加以下內容:

{path: 'detailedview/:type/:id/:queryParams', component: DetailViewComponent}

然后獲取整個段並遍歷該段左右:

this.queryParams = this.route.snapshot.paramMap.get('queryParams');
// assign the values from this.queryParams to other variables

或者應該怎么做?

選項 1:作為可選參數發送

路由配置

const routes: Routes = [
  {path: 'detailedview/:type/:id', component: DetailViewComponent}
];

導航源

navigateToPath() {
  const optionalParams = {
    title: 'Sample',
    q: 'Sample',
    ...
  }
  this._router.navigate(['/detailedview', 'sampleType', 1, {optionalParams: JSON.stringify(optionalParams)}]);
}

導航收件人

import { ActivatedRoute } from '@angular/router';

export class DetailViewComponent implements OnInit {
  constructor(private _actRoute: ActivatedRoute) { }

  ngOnInit() {
    this.optionalParams = JSON.parse(this._actRoute.snapshot.paramMap.get('optionalParams'));
  }
}

結果 URL

/detailedview/sampleType/1;optionalParams=<Object>

選項 2:作為查詢參數發送

路由配置

const routes: Routes = [
  {path: 'detailedview/:type/:id', component: DetailViewComponent}
];

導航源

navigateToPath() {
  const params = {
    title: 'Sample',
    q: 'Sample',
    ...
  }
  this._router.navigate(['/detailedview', 'sampleType', 1], {queryParams: params});
}

導航收件人

import { ActivatedRoute } from '@angular/router';

export class DetailViewComponent implements OnInit {
  constructor(private _actRoute: ActivatedRoute) { }

  ngOnInit() {
    this.type = this._actRoute.snapshot.paramMap.get('type');
    this.title = this._actRoute.snapshot.queryParamMap.get('title'));
    this.q = this._actRoute.snapshot.queryParamMap.get('q'));
  }
}

結果 URL

/detailedview/sampleType/1?title=Sample&q=Sample

好吧,你幾乎自己回答了。 唯一的事情是您不需要聲明您在路由器中使用查詢參數。 從查詢參數中檢索標題的示例:

title= this.route.snapshot.paramMap.get('title');

你可以在這里閱讀更多

暫無
暫無

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

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