【问题标题】:Bind query string params to model in Angular 2将查询字符串参数绑定到 Angular 2 中的模型
【发布时间】:2016-12-15 04:33:27
【问题描述】:

我有一个类似于Google Maps 的应用程序。我想将我的模型与查询字符串参数同步。

这是什么意思?

假设您有一个简单的地图对象。您进入该站点并获得在地图组件中设置的默认边界。但是,当您更改某些内容(平移/缩放/等)时,我希望您的更改也可以在查询字符串中设置以进行位置共享。

如何正确地做到这一点?

【问题讨论】:

    标签: angular angular2-routing


    【解决方案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 的方法。

    不,Angular 2 模型不记录 jQuery 所做的更改。到目前为止,这是该问题的替代解决方案。

    我希望这会有所帮助。

    【讨论】:

    • 在 Angular2+ 代码中使用 jQuery 确实违反了最佳实践。
    【解决方案2】:

    在你的构造函数中注入:

    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 中指定了所有内容,因为您的所有更改都是通过它推送和拉取的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      相关资源
      最近更新 更多