【问题标题】:TypeError: Cannot read property 'Autocomplete' of undefinedTypeError:无法读取未定义的属性“自动完成”
【发布时间】:2020-10-04 06:43:39
【问题描述】:

错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性“自动完成” TypeError:无法读取未定义的属性“自动完成”

当我运行我的 Angular 应用程序时,这个错误不断弹出。它在第 25 行说我的 search.component.ts 文件有问题。这是我的搜索组件

    /// <reference types="@types/googlemaps" />
import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MapsAPILoader } from '@agm/core';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss'],
})
export class SearchComponent implements OnInit {

  autocomplete: any;
  @ViewChild('search')
  public searchElementRef: ElementRef;
  public searchControl: FormControl;

  constructor(private zone: NgZone, 
    private mapsAPILoader: MapsAPILoader) { }

  ngOnInit() {
    this.searchControl = new FormControl();

    this.mapsAPILoader.load().then(() => {
        let autocomplete = new window['google'].maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: [],
        componentRestrictions: {'country': 'US'}
      });
      autocomplete.addListener('place_changed', () => {
        this.zone.run(() => {
          const place: google.maps.places.PlaceResult = autocomplete.getPlace();
          this.searchControl.reset();
        });
      });
    });
  }
}

如何解决这个错误?

提前致谢

【问题讨论】:

  • new window['google'].maps.places 这部分是undefinednull。因此出现错误。
  • @Nikhil 我该如何解决?
  • @Rfoxes:即使出现错误,您的应用程序也能正常编译吗?
  • @Michael D 是的
  • @Rfoxes:我已经发布了答案。

标签: angular typeerror google-places-api


【解决方案1】:

如果应用程序编译正常并出现错误,则它是一个 TS Lint 错误。这是因为 Lint 找不到使用点 . 运算符访问的属性。您可以改用括号符号[] 来解决它。试试下面的

let autocomplete = new window['google']['maps']['places']['Autocomplete'](this.searchElementRef.nativeElement, {
  types: ["address"]
});

更多关于属性访问器的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

【讨论】:

  • 感谢您的解决方案,但这不起作用。我在网上查找,发现可以导入的名为 ngx-google-places-autocomplete 的东西。你知道它和@types/googlemaps 之间的区别吗?或者这只是一种错误的方法?
  • 不熟悉其他模块,无法评论。
猜你喜欢
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
相关资源
最近更新 更多