这在javascript函数内变为null [英] this becomes null inside the javascript function

查看:90
本文介绍了这在javascript函数内变为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java脚本函数,该函数在该函数内部提供了当前的经度,从而发出了一个http调用,例如"this.http.post",但该函数内部的null值

I have java script function which gives current lat long inside that function making an http post call like this "this.http.post" but the value of this null inside the function

我的代码

ngOnInit(): void {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(p) {
          var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
          console.log(p.coords.latitude);
          console.log(p.coords.longitude);
          var dataObj = {
            latitude: p.coords.latitude,
            longitude: p.coords.longitude
          };
          this.http.post('https://XXXXX/datacenteres.php', {
              dataObj
            })
            .subscribe(
              res => {
                console.log(res);
              },
              err => {
                console.log("Error occured");
              }
            );
        }
      }
    }

我在控制台无法读取null的'http'属性"中收到此错误.

I am getting this errors in the console "Cannot read property 'http' of null".

在navigator.geolocation.getCurrentPosition内部(函数(p){这是空的}

Inside navigator.geolocation.getCurrentPosition(function (p) { this is null }

在If语句中,我能够获得"this".

Inside the If statement i am able to get the "this".

推荐答案

尝试这样:

使用函数的.bind(this)结束

ngOnInit(): void {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(p) {
            var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);

            console.log(p.coords.latitude);
            console.log(p.coords.longitude);

            var dataObj = {
                latitude: p.coords.latitude,
                longitude: p.coords.longitude
            };
            this.http.post('https://XXXXX/datacenteres.php', {
                dataObj
            }).subscribe(res => {
                console.log(res);
            }, err => {
                console.log("Error occured");
            });
        }.bind(this));

    }
}

这篇关于这在javascript函数内变为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆