为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

摇曳的蔷薇 2022-09-23 21:43:51
我有多个搜索字段,我想将查询参数存储在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或者应该如何做?
查看完整描述

2 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

选项 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'));

  }

}

生成的网址


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

  }

}

生成的网址


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


查看完整回答
反对 回复 2022-09-23
?
慕丝7291255

TA贡献1859条经验 获得超6个赞

好吧,你几乎自己回答了。唯一的问题是,您不需要声明您正在路由器中使用查询参数。用于从查询参数中检索标题的示例:

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

你可以在这里阅读更多内容


查看完整回答
反对 回复 2022-09-23
  • 2 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信