this becomes null inside the javascript function

后端 未结 3 1855
野性不改
野性不改 2020-12-20 01:09

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

相关标签:
3条回答
  • 2020-12-20 01:17

    Simply store this into a variable and use it inside the callback function. Its' quite handy

    ngOnInit():void {
    var self = this;
    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
                            };
              self.http.post('https://XXXXX/datacenteres.php', {
        dataObj
        })
          .subscribe(
            res => {
              console.log(res);
            },
            err => {
              console.log("Error occured");
            }
          );
    
      }
      }
    
    }
    
    0 讨论(0)
  • 2020-12-20 01:25

    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");
                }
              );
          })
        }
    
    0 讨论(0)
  • 2020-12-20 01:38

    Try like this :

    use .bind(this) end of 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");
                });
            }.bind(this));
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题