Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angular - this becomes null inside the javascript function

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

My code

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");
              }
            );
        }
      }
    }

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use arrow function like below:

if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(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");
            }
          );
      })
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...