【问题标题】:Returning values form function in IONICIONIC中的返回值形式函数
【发布时间】:2020-06-29 09:38:51
【问题描述】:

我尝试学习 IONIC 5。 我使用本地地理定位来返回纬度和经度。 从这个函数中,我需要检索经纬度,然后通过表单发送到服务器。

geolocate()
   {
         this.geolocation.getCurrentPosition().then((resp) => {
         let position = {
           latitude: resp.coords.latitude,
           longitude: resp.coords.longitude
         }
         return position;
    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

使用这个其他功能

login(form: NgForm) {
        this.geolocate();
        this.authService.login(form.value.email, form.value.password, this.latitude, this.longitude).subscribe(
            data => {
                this.alertService.presentToast("Logged In");
            },
            error => {
                console.log(error);
            },
            () => {
                this.dismissLogin();
                this.navCtrl.navigateRoot('');
            }
        );
    }

【问题讨论】:

    标签: angular ionic-framework ionic5


    【解决方案1】:
    async login(form: NgForm) {
            let res = await this.geolocate();
            this.latitude = res.latitude;
            this.longitude = res.longitude;
            this.authService.login(form.value.email, form.value.password, this.latitude, this.longitude).subscribe(
                data => {
                    this.alertService.presentToast("Logged In");
                },
                error => {
                    console.log(error);
                },
                () => {
                    this.dismissLogin();
                    this.navCtrl.navigateRoot('');
                }
            );
        }
    

    【讨论】:

    • geolocate 是一个异步函数,因此您可以访问属性纬度,因为此函数的返回将返回空对象。
    • geolocate() 应该在其块的第一行开头有一个returnreturn this.geolocation.getCurrentPo...
    【解决方案2】:

    你必须回电到getCurrentPosition():

    geolocate() {
    
    return this.geolocation.getCurrentPosition().then((resp) => {
         return {
           latitude: resp.coords.latitude,
           longitude: resp.coords.longitude
         };
       }).catch((error) => {
        console.log('Error getting location', error);
       });
    }
    

    然后,等待结果并将其存储在一个变量中,以便在下一个函数调用中使用它。

    async login(form: NgForm) {
        const coords = await this.geolocate();
    
    this.authService.login(form.value.email, form.value.password, coords.latitude, coords.longitude).subscribe(
            data => {
                this.alertService.presentToast("Logged In");
            },
            error => {
                console.log(error);
            },
            () => {
                this.dismissLogin();
                this.navCtrl.navigateRoot('');
            }
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多