【问题标题】:How to get key from Observable?如何从 Observable 获取密钥?
【发布时间】:2018-03-20 20:08:44
【问题描述】:

我正在尝试使用 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
      }
    ]
  }
]

我的数据库是
我需要这个密钥“4X2NpohlbUa3AA7ri6iHGNm2If93”。
如何获得那个密钥?
我试过 val_2.key 但它显示错误“[ts] Property 'key' does not exist on type 'any[]'. 你是说'keys'吗?”


在 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());
                  }
              });

【问题讨论】:

  • 这既不是 JSON 也不是对象。
  • 需要更改响应数据
  • typescript angular2 with firebase
  • 那是因为你使用了this.itemsRef.valueChanges();。请改用snapshotChanges。检查我的其他answer

标签: json firebase firebase-realtime-database angularfire2


【解决方案1】:

更新:

根据更新的响应数据,您应该使用Object.keys(val)[0] 访问,它给出了键"4X2NpohlbUa3AA7ri6iHGNm2If93" 的值,因为它是第一个键。

根据较早的响应数据:

你的 val 是一个数组。

这应该可行。

Object.keys(val[0]).forEach(function(k1) {
{
    console.log("Key first : "+ k1);
});

【讨论】:

  • 根据更新的响应数据,您应该使用Object.keys(val)[0] 访问,它给出了键“4X2​​NpohlbUa3AA7ri6iHGNm2If93”的值
【解决方案2】:

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

Object.keys(val[0])

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

【讨论】:

    【解决方案3】:

    获取对象中的第一个键

    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]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多