【问题标题】:How to assign snap.val() to the global variable?如何将 snap.val() 分配给全局变量?
【发布时间】:2017-06-25 11:07:57
【问题描述】:

我想将snap.val() 分配给this.Productslike this.Products= snap.val();,但this.Products 在该范围内未定义。

    Products: FirebaseListObservable<any>;
constructor(){

    } 

    ionViewDidLoad(){
      this.angularFire.database.list('/Products').$ref.orderByChild('uid')
     .equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133').on('child_added', function(snap){
                console.log(snap.val().name);
              //this.Products= snap.val();
            });
      }

我在返回 snap 时尝试了以下代码,但我收到了这条消息——No index defined for uid:

snap.forEach(SnapShot=>{
console.log(SnapShot.val().name) 

我的 Firebase 数据库:

"Products" : {
    "-Kbx0i-TFeTyRbNZAZ_8" : {
      "category" : "1",
      "detail" : "xxxxx details",
      "name" : "xxxxx",
      "uid" : "NW1Kq4WB7ReUz2BNknYWML9nF133"
    }

请帮忙。谢谢。

【问题讨论】:

    标签: angularjs firebase ionic-framework firebase-realtime-database ionic2


    【解决方案1】:

    我是这样做的:

    import firebase from "firebase";
    
    const firebaseConfig = {
        your firebaseConfig... 
    };
    
    let app = firebase.initializeApp(firebaseConfig);
    
    let database = firebase.database();
    
    export async function readFromFirebase(userId, key) {
      const ref = database.ref("users/" + userId + "/" + key);
    
      const snapshot = await ref.once("value");
    
      return snapshot.val();
    }
    
    async function main() {
      console.log(await readFromFirebase(109512127, "userName"));
    }
    
    main();
    

    【讨论】:

      【解决方案2】:

      直接回答你问的问题,可以使用ES6 arrow function

      let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
           .equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133');
      query.on('child_added', (snap) => this.Products= snap.val());
      

      或者为了 ES5 兼容性,将 this 声明为变量:

      let self = this;
      let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
           .equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133');
      query.on('child_added', function(snap) {
         self.Products= snap.val();
      });
      

      但实际上,这是一个XY problem,你不想要你认为你想要的东西。

      您所做的是自己重新实现列表,并破坏了 AngularFire2 的全部目的,它代表您处理所有这些同步。

      此外,当您可能想要设置 this.products = [] 然后使用this.products.push(snap.val()) 用于每个 child_added 调用。

      所以你在这里真正想要的是使用 AngularFire 的 built-in queries 并避免这整个混乱:)

      this.products = af.database.list('/Products', {
        query: {
          orderByChild: 'uid',
          equalTo: 'NW1Kq4WB7ReUz2BNknYWML9nF133' 
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-05
        • 1970-01-01
        • 2016-06-25
        • 1970-01-01
        • 1970-01-01
        • 2014-12-03
        • 1970-01-01
        • 2017-02-24
        相关资源
        最近更新 更多