如何从Angular Component中的函数内部访问变量

时间:2018-08-28 12:14:50

标签: angular typescript google-maps

      export class MapsComponent implements OnInit {

      @ViewChild('googleMap') gmapElement: any;
      map: google.maps.Map;  
      data = "initialised";

      ngOnInit() {
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;

          var map =  new google.maps.Map(this.gmapElement.nativeElement, {
                zoom: 7,
                center: {lat: 41.85, lng: -87.65}
          });
          directionsDisplay.setMap(map);
          directionsService.route({
              origin: "terrell hills, tx",
              destination: "alamo heights, tx",
              travelMode: google.maps.TravelMode.DRIVING
            },  (response, status) => {
              if (String(status) === 'OK') {
                directionsDisplay.setDirections(response);
                this.data = "I'm modified in directionsService";
    /**********************************************************
Here the directions are displaying correctly but `this.data`'s value is not changing. What is the reason?
************************************************************/
              } else {
                alert('Directions request failed due to ' + status);
          }
        });
      }
     }

HTML

<span>{{data}}</span> <!---------Here data is always showing as `initialised`, but directions are displaying perfectly---------->

即使使用箭头函数,类成员data的值也不会在函数内部更改。 data的值始终显示initialised。有人可以检查代码中的注释,请告诉我答案。

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试一下是否可行。

import { ChangeDetectorRef, Component, Input, OnInit } from '@angular/core';

  constructor(
    private cdr: ChangeDetectorRef
  ) { }

修改此部分

          if (String(status) === 'OK') {
            directionsDisplay.setDirections(response);
            this.data = "I'm modified in directionsService";
            //this.cdr.markForCheck(); // Changed
            this.cdr.detectChanges(); 
          } else {
            alert('Directions request failed due to ' + status);
      }