2016-08-09 51 views
0

我有一個類似於Google Maps的應用程序。我想用查詢字符串參數來同步我的模型。將查詢字符串參數綁定到Angular 2中的模型

這是什麼意思?

假設你有一個簡單的地圖對象。您進入該網站,並獲得在地圖組件中設置的默認邊界。但是當你改變一些東西時(平移/縮放/等),我希望你的改變也可以在查詢字符串中設置,以便分享位置信息。

如何正確執行此操作?

回答

1

我會告訴你我實現它的方式,但我不確定它是否是正確的方法。

的理念是:

首先,我添加了一個隱藏的輸入記錄同時映射對象的變化:

<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

而且,角度2模型不記錄jQuery所做的更改。到目前爲止,這是解決這個問題的另一種方法。

我希望這會有所幫助。

+1

在Angular2 +代碼中使用jQuery實際上違背了最佳實踐。 – DanilF

0

進樣在你的構造:

activatedRoute: ActivatedRoute, 
router: Router 

要更新,你可以使用的網址:

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中指定所有內容,因爲所有更改都是推送的編輯並通過它。

相關問題