简体   繁体   中英

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

I have multiple search fields and I want to store the query parameters in the URL but I am not sure how to do it.

The path of the component looks like this:

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

:type and :id are fixed values. After those values, I need to append such an url segment q=...&title=...&... which length varies regarding which field one has filled. Then I need to fetch somehow the data.

Do you think I should add the following to my path:

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

and then get the whole segment and iterate through that segment or so:

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

or how should one do it?

Option 1: Send as optional parameters

Route config

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

Navigation source

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

Navigation recipient

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'));
  }
}

Resulting URL

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

Option 2: Send as query parameters

Route config

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

Navigation source

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

Navigation recipient

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'));
  }
}

Resulting URL

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

well, you almost answered it yourself. the only thing is that you don't need to declare that you are using query params in the router. example for retrieving title from query params:

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

you can read more in here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM