从打字稿中的另一个函数调用一个函数

Calling a function from another function in typescript

我已经在 ngOnInit() 上调用了一个函数,现在我正在尝试从前一个函数调用另一个函数,但我无法从第二个函数中获得结果

ngOnInit() {
    this.mapsAPILoader.load().then(() => {
        let autocomplete = new google.maps.places.Autocomplete(this.searchElement.nativeElement, {types: ['address']});
        autocomplete.addListener('place_changed', () => {
            this.ngZone.run(() => {
                let place: google.maps.places.PlaceResult = autocomplete.getPlace();
                if (place.geometry === undefined || place.geometry === null) {
                    return;
                }
                this.codeAddress(place.formatted_address, 'pickup');
            });
        });
    });
}

codeAddress(address: string, type) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, (results, status) => {
        if (status == google.maps.GeocoderStatus.OK) {
            this.getdistance();
        } else {
            alert('Request failed.');
        }
    });
}

getdistance() {
    console.log('get distance called');
}

在代码中,我试图从 codeaddress() 函数调用 getdistance() 函数。但它给我的错误是 this.getdistance() 不是函数

使用箭头函数代替 function 以在其中使用 this 指针。

codeAddress(address: string, type) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, (results, status) => {
        if (status == google.maps.GeocoderStatus.OK) {
            this.getdistance();
        } else {
            alert('Request failed.');
        }
    });
}

您正在尝试从回调中访问 this,您可以使用 function(){}.bind(this) 使函数使用正确的上下文,或者使用 ES6 箭头函数。

geocoder.geocode({ 'address': address }, (results, status) => {
    if (status == google.maps.GeocoderStatus.OK) {
        this.getdistance();
    }
    else {
        alert("Request failed.");
    }
});

回答预编辑;

这是因为你有一个回调函数 function(){..} 而不是 () => {..}。因此,您的 this 指的是 function 内部的上下文,而不是完整的 class this 范围。

要么改成箭头函数,要么在函数中明确设置this

var self = this
function(){
   this.getDistance()
}

当你进入函数时,this 的上下文会发生变化,所以执行类似下面的操作,否则使用 [=12 的箭头函数=]

codeAddress(address: string,type) {
     const self = this;
     var geocoder = new google.maps.Geocoder();
     geocoder.geocode({ 'address': address }, function (results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
              self.getdistance();
           } else {
              alert("Request failed.");
           }
       });
  }