【问题标题】:Why am I unable to access class properties inside of a passed function of an Angular component?为什么我无法访问 Angular 组件的传递函数内的类属性?
【发布时间】:2021-09-12 05:31:11
【问题描述】:

我在 Angular 组件中使用 HTML 5 地理位置:

...
    export class AngularComponent {
    ...
        constructor(private db: DatabaseService) {}

        // this function is assigned to an HTML button
        logCoords(message, action) {
        navigator.geolocation.getCurrentPosition(this.success, this.error, this.options);
        }

        success(pos) {
            function time() {
            ...
            }
            var crd = pos.coords;
            var lat = crd.latitude
            var long = crd.longitude

            let newCoordinates = {'lat': lat, 'long':long, 'time': time}
            this.db.addLocation(newCoordinates)
        }
    ...
    }
...

我想使用 Angular 服务将 getCurrentPosition 方法的结果存储在索引数据库中,但我无法访问组件类的任何属性(this.db 为空)。

为什么我无法在成功函数中访问 this.db 以及如何解决这个问题?

【问题讨论】:

  • 你能在stackblitz上分享一些代码吗?
  • 添加模块代码,你忘了在模块中注入服务。
  • 模块被注入并在模板的其他部分工作;在成功内部,console.log 显示 this.db 为空。我认为这与我对 javascript 缺乏了解有关,因为成功功能正在地理定位库的其他地方使用...
  • success = (pos) => {替换success(pos) {
  • 有道理。希望我有一个技术描述为什么这不起作用。愿上帝保佑你。

标签: javascript angular typescript geolocation


【解决方案1】:

问题在于以下行:

navigator.geolocation.getCurrentPosition(this.success, this.error, this.options);

在上面的行中,您只是将this.success 作为回调传递,而没有为其设置上下文。因此,在这种情况下,根据 javascript 原则,this 将始终在您期望组件引用时引用窗口对象。
要解决此问题,您必须在传递 this.success 之前设置上下文(组件实例),为此目的,javascript 提供了 bind() 函数。

试试下面的代码(非常简单的修复)-

navigator.geolocation.getCurrentPosition(this.success.bind(this), this.error.bind(this), this.options);

有关 bind() 函数的更多详细信息,请参阅以下链接 -

https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_objects/Function/bind

【讨论】:

    【解决方案2】:

    因为您在将方法作为回调传递时丢失了上下文this。 您可以通过多种方式解决此问题:

    logCoords(message, action) {
        // bind context
        navigator.geolocation.getCurrentPosition(this.success.bind(this), this.error.bind(this), this.options);
    }
    

    logCoords(message, action) {
        navigator.geolocation.getCurrentPosition(this.success, this.error, this.options);
    
        success = (pos) => {} // <= arrow function
        error = () => {}      // <= arrow function
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-01
      • 2012-10-30
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多