【问题标题】:Passing map distance to ngModel in Ionic 2在 Ionic 2 中将地图距离传递给 ngModel
【发布时间】:2017-04-01 05:29:57
【问题描述】:

这是代码的一部分:

calculateAndDisplayRoute(directionsService, directionsDisplay) {

  if((this.origin.query !== '') && (this.destination.query !== '')) {

    directionsService.route({
      origin: this.origin.query,
      destination: this.destination.query,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);    
        var total = 0;
        var route = directionsDisplay.getDirections().routes[0];

        for (var i = 0; i < route.legs.length; i++) {
          total += route.legs[i].distance.value;
        }

        total = total / 1000;

        this.distance = total << PROBLEM

      } else {
        window.alert('Directions request failed due to ' + status);
      }

  });

  } else {
    return;
}

这将获取两个地方之间的路线和距离(以公里为单位)(总变量)。问题是我不能在这个回调之外使用变量。我想将它绑定到一个 ngModel 以便进一步手动更改/使用。

我知道我需要使用 ngZone 来更新模型,但我无法将 zone 传递给回调,一些帮助?^^

<ion-input type="number" (keyup)="onKey($event)" [(ngModel)]="distance"></ion-input>

【问题讨论】:

    标签: google-maps angular google-maps-api-3 ionic2


    【解决方案1】:

    问题根本不是ngZone。事实上,您正在使用更改 this 值的常规函数​​。所以this.distance 中的function(response,status) 是不同的。 试试:

    (response, status)=> {
          if (status === 'OK') {
            directionsDisplay.setDirections(response);    
            var total = 0;
            var route = directionsDisplay.getDirections().routes[0];
    
            for (var i = 0; i < route.legs.length; i++) {
              total += route.legs[i].distance.value;
            }
    
            total = total / 1000;
    
            this.distance = total << PROBLEM
    
          } else {
            window.alert('Directions request failed due to ' + status);
          }
    
      }
    

    箭头函数Reference

    【讨论】:

    • 是的,但即使使用箭头函数,如果我尝试在回调之外使用 console.log(this.distance),它也会以未定义的方式响应。这就是我卡住的地方。
    • 取决于 .route 是否是异步函数,在这种情况下,您的 console.log 外部将在箭头函数执行之前打印出来。在模板的情况下,视图将在以下情况下更新箭头函数被调用
    • 看起来可以正常工作,非常感谢.. 我没有检查我所做的每一个更改的视图,只检查控制台:S 再次感谢 ^^
    猜你喜欢
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2019-05-02
    相关资源
    最近更新 更多