2017-06-04 31 views
0

我的应用程序(ionic 1.x and firebase)的常用用法是一次推送一个对象,但可能会出现这样的情况,即必须将多个对象添加到数据库中之后。官方文件没有提到这种情况。这是每次按一个对象的代码:Firebase和Ionic 1.x - 无法一次向DB添加多个对象

this.addExpenseToDB = function (expense, uid) { 
    var newExpenseKey = firebase.database().ref().child('expenses').push().key; 
    var updates = {}; 
    var keyByDate = "someKey"; 

    updates['/user-data/' + uid + '/' + keyByDate + '/'+ newExpenseKey] = expense; 

    return firebase.database().ref().update(updates); 
}; 

两个问题,A:我如何可以一次推几个对象? B如何获得确认(承诺?回调?)数据已成功保存到数据库?该文档同样缺少以下信息:\

回答

1

您可以扇动一个对象,类似于您现在正在做的事情。首先,你需要传递的对象数组添加到数据库中,然后将它们扇形出像你现在做一个循环:

this.addExpenseToDB = function (arr) { 
    // arr: [{expense: ..., uid: ...}]; 

    var updates = {}; 
    for(var i=0; i<arr.length; i++) { 
     var newExpenseKey = firebase.database().ref().child('expenses').push().key; 
     var keyByDate = "someKey"; 
     updates['/user-data/' + arr[i].uid + '/' + keyByDate + '/'+ newExpenseKey] = arr[i].expense; 
    } 

    return firebase.database().ref().update(updates); 
}; 

push(...)返回一个承诺,所以监听响应:

this.addExpenseToDB([expense: ..., uid: ...]) 
    .then(response => { 

    }) 
    .catch(error => { 

    }); 

带回调

this.addExpenseToDB = function (arr, callback) { 
    ... 
    return firebase.database().ref().update(updates, function(error) { 
     callback(error); 
    }); 
} 
this.updated = function(error) { 
    if(error) 
     // error 
    else 
     // success 
} 
this.addExpenseToDB([expense: ..., uid: ...], this.updated); 
+0

感谢您的帮助。我没有使用'es6',我还能享受'promise'功能吗? – undroid

+0

是的,写一个回调。很多关于如何做到这一点的问题。 – theblindprophet

+0

我不确定我是否正确。你能否看到最新的问题? – undroid

相关问题