问题
I have an app similar to Google Maps. I would like to sync my model with query string params.
What do I mean by this?
Suppose you have a simple map object. You enter the site and you get default bounds set in the map component. But when you change something (pan/zoom/etc.), I want your changes to be set also in query string for location sharing things.
How to do this properly?
回答1:
I will show you the way I implemented it but I'm not sure if it's a proper way to do it though.
The idea is:
First, I add a hidden input to record the change of map object simultaneously:
<input hidden id='hiddenMapValue' #hiddenInput>
#hiddenInput is there for a purpose and you'll see it.
Then, every time map object changes, assign the value to this hidden input, for example:
$("#hiddenMapValue").val(place.geometry.location).trigger('change');
In your component:
@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; is how you get a hold on hidden input #hiddenInput.
And no, angular 2 model does not record changes made by jQuery. This is an alternate solution to this problem, so far.
I hope this will help.
回答2:
Inject in your constructor:
activatedRoute: ActivatedRoute,
router: Router
To update the URL you can use:
this.router.navigate(
[this.param],
{
queryParams: {
queryParamKey: this.queryParam,
}
});
To subscribe to changes to the URL changing you can use:
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'];
});
This way you'll be able to make sure that everything is specified in the URL, since all your changes are pushed and pulled through it.
来源:https://stackoverflow.com/questions/38845490/bind-query-string-params-to-model-in-angular-2