【问题标题】:Ionic + Angular2 google maps layer event listener model bindingIonic + Angular2 谷歌地图层事件监听器模型绑定
【发布时间】:2018-01-06 08:42:44
【问题描述】:

我有一个用标记初始化的地图。每当我单击标记时,我都想更新 Ngmodel。最终这应该反映在离子搜索栏中。每当加载视图时,我都会调用 initMap(),它将地图与此侦听器一起加载:

google.maps.event.addListener(layer, 'click', function(e) {
      this.searchValue = e.row['name'].value;
});

在我的模板中:

<ion-searchbar [(ngModel)]="searchValue"></ion-searchbar>

每当我在声明中将值设置为 searchValue 时,它​​都会显示在离子搜索栏中,但在单击标记后不会显示。标记单击事件确实有效,因为如果我控制台记录 e.row['name'].value ,我会得到正确的值,它似乎没有绑定。

【问题讨论】:

  • 您是否尝试过在NgZone 方法run() 中包装this.searchValue = e.row['name'].value;this.zone.run(() =&gt; { this.searchValue = e.row['name'].value; });
  • 我现在已经在我的模块中导入了 NGZone,也在构造函数中声明了它。添加了这个: this.zone.run(() => { this.searchValue = e.row['name'].value; });在 addlistener 方法中,我得到:无法读取未定义的属性“运行”
  • 只需在您的组件中导入NgZone。不在模块中。
  • 对不起,我在我的组件中这样做了。从“@angular/core”导入。在我的构造函数私有区域中:NgZone。然后是 addListener 函数中的区域代码。然后它给了我那个错误。
  • 我通过这样做修复了它: google.maps.event.addListener(layer, 'click', (e) => { this.searchValue = e.row['name'].value; } )};但是,该值的更新速度非常慢。因此,当我单击标记时,它会在 10 多秒后更新。知道如何解决吗?

标签: javascript angular google-maps-api-3 ionic-framework angular-ngmodel


【解决方案1】:

尝试导入NgZone 并利用其run() 方法,显式使代码在Angulars 区域内运行,并在之后触发更改检测。还将function(e){...} 更改为(e) =&gt; {},这与this 无关。

import { Component, NgZone } from '@angular/core';

@Component({
    ...
})
export class SomeComponent{
    someValue: string;

    constructor(private zone: NgZone){}

    initMap(){
        ...
        google.maps.event.addListener(layer, 'click', (e) => {
            this.zone.run(() => {  
                this.searchValue = e.row['name'].value;
            });
        });
    }

    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多