我有多个搜索字段,我想把查询参数存储在URL中,但我不知道该怎么做。
组件的路径是这样的。
const routes: Routes = [
{path: 'detailedview/:type/:id', component: DetailViewComponent}
];
:type
和 :id
是固定值。在这些值之后,我需要附加这样一个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
还是应该怎么做?
路线配置
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>
路线配置
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
唯一的问题是,你不需要在router.example中声明你正在使用query params从query params中检索标题。
title= this.route.snapshot.paramMap.get('title');
你可以阅读更多的内容 此处