【问题标题】:Get key of a new element获取新元素的键
【发布时间】:2015-05-17 07:28:43
【问题描述】:

我有一个service 有这个功能:

this.addSubject = function(categId, data){      
 $firebase(url.child('discussions').child(categId)).$push(data).then(function (newChildRef) {
    console.log("added record with id " + newChildRef.key());
    });      
};

我在Controller 中调用该函数。但我想恢复新的 ID newChildRef.key(),以便在我的 Controller 中使用它。但如果我做出回报,那就什么都没有了。

有没有办法保存这个id

或者是否可以在这个函数中调用我服务的其他函数?

【问题讨论】:

  • 您能否仅返回 $firebase(url.child('discussions').child(categId)).$push(data) 部分并从控制器中的 .then(...) 中访问密钥?
  • 请注意,AngularFire 是最近发布的 1.0.0,$firebase 现在已弃用。您可以改用$firebaseObject$firebaseArray
  • @bryan 我完全忘记尝试返回firebase(url.child('discussions').child(categId)).$push(data)...但它有效!还有@SinanBolel,我知道$firebase 现在已弃用,但我使用的是0.9.2 版本:)

标签: angularjs asynchronous firebase angularfire


【解决方案1】:

您不能从这些函数返回,因为它们是承诺合同的一部分,并且将来会异步发生。相反,您必须做的是让您的函数调用控制器中的方法来告诉它已加载的键。然后控制器可以响应,UI 将跟随。你如何让你的函数知道在哪里调用?

让控制器将自己内部的函数传递给您的服务,当结果已知时,该服务应该调用该函数。

例如

var target = function(id) { // processes id
};

// call the function in your service passing the receiving function
service.addSubject('catid', 'data', target);

您的服务将需要接收该功能并对其进行处理

this.addSubject = function(categId, data, callback){
$firebase(url.child('discussions').child(categId)).$push(data).then(function (newChildRef) {
    console.log("added record with id " + newChildRef.key());

    // send to the callback
    callback(newChildRef.key());
  });      
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2014-03-10
    相关资源
    最近更新 更多