angular - 从 typescript 中的另一个函数调用一个函数

标签 angular angular7

我已经在 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() is not a function

最佳答案

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

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

关于angular - 从 typescript 中的另一个函数调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57864426/

相关文章:

typescript - 类型 'Promise<any>' 缺少以下属性

angular - 如何在组件中测试FormGroupDirective?

javascript - 错误类型错误 : Cannot read property 'formData' of undefined

来自另一个组件的 Angular 9 调用函数

node.js - 执行 "npm install"时出现很多错误

javascript - 下载大图像的小版本 - 客户端 - 没有后端功能 - javascript

angular - Ngx-quill 工具栏自定义不起作用 - quill 无法导入模块

angular - 在 Angular 组件之间共享字符串

Angular 2 : Route redirect with AuthGuard

redux - 如何使用 ngFor 以角度获取和显示 ngrx 存储数据