【问题标题】:Firebase AngularJS array map()Firebase AngularJS 数组映射()
【发布时间】:2017-10-23 04:51:02
【问题描述】:

我有多个要循环的 firebase 项目,它们有名称、categoryId、lat、lon。

我正在尝试计算距 2 lat,lon 的距离(一个是 firebase 中的那个),另一个是用户的位置。

这一切都很好,我也可以很好地计算出来。但是,如何将新变量注入/映射到我订阅的 firebase 数组中?

this.categoryId = this.navParams.get('categoryId');
afoDatabase.list('/list', {query: {
    orderByChild: "categoryId",
    equalTo:  parseInt(this.categoryId)
}}).subscribe(listItems => {
    this.items = listItems; //need to add distance within array
    loadingPopup.dismiss().catch(() => {});
});

例如,我有一个名为 distance 的变量,它计算所有内容并具有值。如何在 this?items 中添加它 - 这样我就可以从 HTML 端调用它?

感谢您的帮助:)

【问题讨论】:

    标签: angularjs arrays firebase dictionary ionic-framework


    【解决方案1】:

    要注入,首先创建一个函数并创建一个变量(例如 this.distance)并在此变量上获取函数的值。之后,使用 for 循环根据长度递增 - 并使用 this.items[i]["distance"] 添加到每个循环。例如:

    this.categoryId = this.navParams.get('categoryId');
      afoDatabase.list('/list', {query: {
          orderByChild: "categoryId",
          equalTo:  parseInt(this.categoryId)
      }}).subscribe(listItems => {
            this.items = listItems;
    
            this.geolocation.getCurrentPosition({timeout:15000}).then((resp) => {
    
             this.myLat = resp.coords.latitude;
             this.myLong = resp.coords.longitude;
    
    
            }).catch((error) => {
              console.log('Error getting location', error);
            });
    
    
    
            for (var i = 0, len = this.items.length; i < len; i++) {
                this.distance = this.calculateDistance(this.myLat, this.myLong, this.items[i].lat, this.items[i].lng);
                this.items[i]["distance"] = Math.round(this.distance);
                  console.log('testing myLat', this.myLat)
                  console.log('testing myLong', this.myLong)
              }
    
              console.log('testing inject', this.items)
            loadingPopup.dismiss().catch(() => {});
      });
    

    功能

    calculateDistance(lat1:number,lon1:number,lat2:number,lon2:number){
    
      let R = 6371; // km
      let dLat = (lat2 - lat1) * Math.PI / 180;
      let dLon = (lon2 - lon1) * Math.PI / 180;
      let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                      Math.sin(dLon / 2) * Math.sin(dLon / 2);
      let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      let d = R * c;
        return d;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 2015-04-20
      • 2017-01-11
      • 1970-01-01
      • 2020-11-28
      • 2020-01-31
      • 1970-01-01
      相关资源
      最近更新 更多