如何从Observable获取密钥?

时间:2018-03-20 08:59:34

标签: json firebase firebase-realtime-database angularfire2

我正在尝试使用angular 2和typescript从firebase读取数据 我的代码

export class DashboardComponent implements OnInit {
    itemsRef: AngularFireList<any>;
    items: Observable<any[]>;


      constructor(  afDatabase: AngularFireDatabase) {

        this.itemsRef = afDatabase.list('/user_orders/louro');
        this.items = this.itemsRef.valueChanges();

        this.items.subscribe(val_2 => {

         alert(val_2.keys());

            val_2.forEach(function (value2) {
            {

                Object.keys(value2).forEach(function(k2) {
                 {

                     // k is key
                     let count = Object.keys( (value2[k2] )).length;
                     console.log("New order key "+k2);

                     for(let i=0;i<count;i++){
                         console.log(i+"=>  "+JSON.stringify (value2[k2][i]));

                     }

                }
            });



            }
          })
        });




      }



  ngOnInit() {
  }

} 


并且在val_2上只包含

[
  {
    "-L7rtl2NesdOYVD4-bMs": [
      {
        "ads_show": false,
        "brand": "",
        "buttonLabel": "Add to cart",
        "child": "fruits",
        "decrn": "testing for demonstrate",
        "key": "-L7rtXc0pMQhi1ClK-pP",
        "mid": "fresh fruits",
        "note": "",
        "orderInfo": {
          "message": "nil",
          "methode": "cash on delivery",
          "status": "nil",
          "time": 1521356314040,
          "time2": 1521356254115
        },
        "p_id": 73,
        "p_name": "testing",
        "position": 0,
        "primary_key": "testinglouro",
        "qty": {
          "m_qty": 1,
          "qty": 23,
          "unite": "1kg",
          "user_intput_qty": 2
        },
        "quantity_new": 2,
        "querykey_shop_name_top": "louro_fruits",
        "sellerName": "louro",
        "sellonline": true,
        "seo": {
          "meta_descrption": "",
          "meta_title": ""
        },
        "service": false,
        "serviceMessage": "Please enter your complaint details",
        "serviceTitle": "Service Requesting",
        "shopname": "louro",
        "shopview": false,
        "summery": "nil",
        "tags": "",
        "top": "fruits",
        "uid": "IG2SxH6Gcabr3QVLz9jE9Wwweh62",
        "variants": [
          {
            "img_position": 0,
            "prize": {
              "mrp": 58,
              "selling_prize": 45,
              "tax": 0
            },
            "qty": {
              "m_qty": 1,
              "qty": 23,
              "unite": "1kg",
              "user_intput_qty": 2
            },
            "shipping": {
              "minmumbuy": 0,
              "s_cost": 0,
              "s_dlts": ""
            }
          }
        ],
        "variants_position": 0
      }
    ]
  }
]

我的数据库是enter image description here
我需要这个键“4X2​​NpohlbUa3AA7ri6iHGNm2If93”。
如何获得该键?
我试过val_2.key           但它显示错误“[ts]属性'键'在类型'任何[]'上不存在。你的意思是'键'吗?”


在java中我使用下面的代码并正常工作dataSnapshot1.getKey();

 FirebaseDatabase database = FirebaseDatabase.getInstance();
              DatabaseReference myRef = database.getReference(getResources().getString(R.string.user_orders)+"/"+
                      shop_name,getContext()));
              myRef.addListenerForSingleValueEvent(new ValueEventListener() {
                  @Override
                  public void onDataChange(DataSnapshot dataSnapshot) {
                      // This method is called once with the initial value and again
                      // whenever data at this location is updated.
                      //  MainAction.setDefaults("OpenCategories",dataSnapshot.toString(),getActivity());
                      if (dataSnapshot.hasChildren()) {
                          for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                              orderDetails1 = null;
                              orderDetails1 = new OrderDetails();
                              if (dataSnapshot1.hasChildren()) {
                                  int id = -1;
                                  for (DataSnapshot dataSnapshot2 : dataSnapshot1.getChildren()) {
                                      id = id + 1;
                                      if (dataSnapshot2.hasChildren()) {
                                          int productid = -1;
                                          for (DataSnapshot dataSnapshot3 : dataSnapshot2.getChildren()) {
                                              productid = productid + 1;
                                              if (dataSnapshot3.hasChildren()) {
                                                  orderDetails1.productmillaList.add(dataSnapshot3.getValue(Productmilla.class));
                                              }
                                              orderDetails1.productmillaList.get(productid).setPosition(Integer.parseInt(dataSnapshot3.getKey()));
                                              orderDetails1.productmillaList.get(productid).setId(dataSnapshot2.getKey());
                                          //    Log.d("key2",dataSnapshot2.getKey()+"  "+productid);
                                          }
                                      }

                                      //orderDetails1.productmillaList.get(id).setId(dataSnapshot2.getKey());
                                  }
                              }
                              orderDetails1.key = dataSnapshot1.getKey();
                              orderDetails.add(orderDetails1);

                          }
                          getaddress(orderDetails);
                      } else   mProgressBar.setVisibility(View.GONE);

                  }

                  @Override
                  public void onCancelled(DatabaseError error) {
                      // Failed to read value
                      mProgressBar.setVisibility(View.GONE);
                      Log.w("dd", "Failed to read value."+ error.getMessage());
                  }
              });

3 个答案:

答案 0 :(得分:1)

更新:

根据更新后的回复数据,您应该使用Object.keys(val)[0]进行访问,"4X2NpohlbUa3AA7ri6iHGNm2If93"会为密钥Object.keys(val[0]).forEach(function(k1) { { console.log("Key first : "+ k1); }); 提供值,因为它是第一个密钥。

根据旧的回复数据:

你的val是一个数组。

这应该有用。

select *
from
 (
    select tab.*,
       count(*) over (partition by Name) as cnt,
       first_value(Occupation) over (partition by Name order by StartDate) as occ#1
       max(Occupation) over (partition by Name) as occ#2 -- simpler than LAST_VALUE
    from tab
 ) st
where cnt = 2             -- excatly 2 rows
  and occ#1 ='Journalist' -- 1st occupation
  and occ#2 = 'Baker'     -- 2nd occupation

答案 1 :(得分:0)

在您的JSON中,val是一个数组。

Object.keys(val[0])

将为您提供该数组的第一个元素的键,这是您所追求的。

答案 2 :(得分:0)

获取对象中的第一个键

Object.keys(val)[0]; //returns 'first key'

[https://stackoverflow.com/a/11509718/7458082][1]

迭代对象

Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});

[https://stackoverflow.com/a/11509718/7458082][1]