我有一个类似于Google Maps
的应用。我想将我的模型与查询字符串参数同步。
这是什么意思?
假设您有一个简单的地图对象。您进入该站点并获得在地图组件中设置的默认边界。但是当你改变某些东西(平移/缩放/等)时,我希望你的更改也可以在查询字符串中设置以进行位置共享。
怎么做得好?
我会告诉你我实现它的方式,但我不确定它是否是一种正确的方法来实现它。
这个想法是:
首先,我添加一个隐藏的输入来同时记录地图对象的变化:
<input hidden id='hiddenMapValue' #hiddenInput>
#hiddenInput
有一个目的,你会看到它。
然后,每次地图对象更改时,将值分配给此隐藏输入,例如:
$("#hiddenMapValue").val(place.geometry.location).trigger('change');
在您的组件中:
@ViewChild('hiddenInput') hiddenInput: ElementRef;
ngAfterViewInit(){
$(this.hiddenInput.nativeElement).on('change', (e)=>{
this.onInputChanged(e);
});
}
private onInputChanged(e): void{
//This is your changed location value
console.log(e.target.value);
}
@ViewChild('hiddenInput') hiddenInput: ElementRef;
是你如何抓住隐藏的输入#hiddenInput
。
不,angular 2模型不记录jQuery所做的更改。到目前为止,这是该问题的替代解决方案。
我希望这将有所帮助。
在构造函数中注入:
activatedRoute: ActivatedRoute,
router: Router
要更新您可以使用的URL:
this.router.navigate(
[this.param],
{
queryParams: {
queryParamKey: this.queryParam,
}
});
要订阅更改URL的更改,您可以使用:
this.activatedRoute.paramMap.subscribe((params: ParamMap) => {
// remember to add /:paramKey to your routing!
this.param = params.get('paramKey');
this.update();
});
this.activatedRoute.queryParams.subscribe((params: { [key: string]: any }) => {
this.queryParam = params['queryParamKey'];
});
这样,您就可以确保在URL中指定了所有内容,因为所有更改都会通过它进行推送和拉取。