离子全局变量使用

ionic global variable using

我是 ionic 的新手,所以我使用全局变量在 service.ts 中接收结果,但问题是 我在我的 ngOnit 和服务的函数中都打印出了结果,我在 service.ts 的函数中得到了我想要的,所以我认为函数本身是有效的,但是当我在 ngOnit 中打印结果时,它使用全局变量来打印出来的结果,显示undefined,请问是什么问题?

export class OutcomePage implements OnInit {
 data: any;
 map;
 userlat;
 userlng;
 public placelat;
 public placelng;
 public pos;
 public userpos;
 constructor(private route: ActivatedRoute, private router: Router ,private zone: NgZone,private geolocation: Geolocation , private service : ControllerserviceService) { 
   this.route.queryParams.subscribe(param=>{
     if(param && param.special){
       this.data = JSON.parse(param.special);
     }
   });
 }
ngOnInit(): void{
    this.pos = this.service.getdistance();
    //console.log(this.userlat);
    this.userpos = this.service.getpos();
    console.log(this.pos);
    console.log(this.userpos)
  }
getpos(){
    this.geocoder.geocode({ 'address': "xxxxxxxxxxxxxxx" },  (results, status)  => { 
      let pos;
        if (status == google.maps.GeocoderStatus.OK) {
            //console.log(results[0].geometry.location.lat());
            pos = {
              lat: results[0].geometry.location.lat(),
              lng: results[0].geometry.location.lng()
            };
            console.log(pos);
            return pos;
        }
    });
  }

经过几次测试,我将问题缩小到这段代码测试

getdistance(){
    this.geolocation.getCurrentPosition().then((resp) => {
      this.userpos = {
        lat: resp.coords.latitude,
        lng: resp.coords.longitude
      };
      console.log(this.userpos);
      //console.log(google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(userpos.lat, userpos.lng), new google.maps.LatLng(this.pos)));   
      //console.log(resp.coords.latitude);
    })
    console.log(this.userpos);
    return this.userpos;
  }

所以第一个控制台日志显示了我想要的确切结果,但第二个控制台日志显示 "undefined",我认为这就是问题所在,但我无法弄清楚

确保没有数据会被转移到其他页面,因为在 getpos() 中你 decalred let pos 所以它会将变量保存在 decalred pos 而不是 public pos,以便将它保存在publoc pos,您需要进行此更改:

getpos(){
    this.geocoder.geocode({ 'address': "xxxxxxxxxxxxxxx" },  (results, status)  => { 
        if (status == google.maps.GeocoderStatus.OK) {
            //console.log(results[0].geometry.location.lat());
            this.pos = {
              lat: results[0].geometry.location.lat(),
              lng: results[0].geometry.location.lng()
            };
            console.log(this.pos);
            return this.pos;
        }
    });
  }

现在值应该绑定到 public pos 因为我们用它来指向它而不是 decaring 一个名为 pos 的新变量。