在 URL 中动态存储查询参数的最佳方式是什么?

我有多个搜索字段,我想将查询参数存储在URL中,但我不确定该怎么做。


组件的路径如下所示:


const routes: Routes = [

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

];

:type并且是固定值。在这些值之后,我需要附加这样一个URL段,其长度因已填充的字段而异。然后我需要以某种方式获取数据。:idq=...&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

或者应该如何做?


摇曳的蔷薇
浏览 107回答 2
2回答

慕虎7371278

选项 1:作为可选参数发送路由配置const routes: Routes = [&nbsp; {path: 'detailedview/:type/:id', component: DetailViewComponent}];导航源navigateToPath() {&nbsp; const optionalParams = {&nbsp; &nbsp; title: 'Sample',&nbsp; &nbsp; q: 'Sample',&nbsp; &nbsp; ...&nbsp; }&nbsp; this._router.navigate(['/detailedview', 'sampleType', 1, {optionalParams: JSON.stringify(optionalParams)}]);}导航收件人import { ActivatedRoute } from '@angular/router';export class DetailViewComponent implements OnInit {&nbsp; constructor(private _actRoute: ActivatedRoute) { }&nbsp; ngOnInit() {&nbsp; &nbsp; this.optionalParams = JSON.parse(this._actRoute.snapshot.paramMap.get('optionalParams'));&nbsp; }}生成的网址/detailedview/sampleType/1;optionalParams=<Object>选项 2:作为查询参数发送路由配置const routes: Routes = [&nbsp; {path: 'detailedview/:type/:id', component: DetailViewComponent}];导航源navigateToPath() {&nbsp; const params = {&nbsp; &nbsp; title: 'Sample',&nbsp; &nbsp; q: 'Sample',&nbsp; &nbsp; ...&nbsp; }&nbsp; this._router.navigate(['/detailedview', 'sampleType', 1], {queryParams: params});}导航收件人import { ActivatedRoute } from '@angular/router';export class DetailViewComponent implements OnInit {&nbsp; constructor(private _actRoute: ActivatedRoute) { }&nbsp; ngOnInit() {&nbsp; &nbsp; this.type = this._actRoute.snapshot.paramMap.get('type');&nbsp; &nbsp; this.title = this._actRoute.snapshot.queryParamMap.get('title'));&nbsp; &nbsp; this.q = this._actRoute.snapshot.queryParamMap.get('q'));&nbsp; }}生成的网址/detailedview/sampleType/1?title=Sample&q=Sample

慕丝7291255

好吧,你几乎自己回答了。唯一的问题是,您不需要声明您正在路由器中使用查询参数。用于从查询参数中检索标题的示例:title=&nbsp;this.route.snapshot.paramMap.get('title');你可以在这里阅读更多内容
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript