如何修改延迟保证范围内的firebase ref值

时间:2015-01-19 12:21:51

标签: angularjs firebase promise angularfire restangular

我有一个使用Firebase和AngularFire的简单聊天系统。

  • 我想为用户查看的每条消息添加一些用户元数据。
  • 元数据来自使用基于promises的客户端(Restangular)的Api,元数据也与消息绑定,因此一旦响应来自api,元数据就会添加到消息中。
  • 我希望每次收到新邮件时都这样做。
  • 如果用户来到会话并且没有查看X消息历史记录,我想为每条消息执行此操作。

我正在努力建设,我知道我做错了。我正在搞乱范围等。

问题是由于错误的消息密钥,元数据有时会被添加到错误的消息中。

非常感谢任何帮助。


这里有一些代码进行了评论,以说明问题。

消息示例的Firebase参考:

  test
    -JeMIr3b7O4HLQTutPUO
      content: "Hi my friend, how are you"
      created_by: "John"
      metadata
        maria: "Liked the message, Cloudy Wheather 90 degrees, with a happy mood, and viewed on monday"
        peter: "Disliked the message, Sunny Wheather 180 degrees, with a sadd modd, and viewed on freiday "
    -JeMIwh7VrNaz_eVaPhe 
      ...
    -JeMIzg9UrAzU8QXW-ze
      ...
    -JeMRORvKTOLul5Ib6_l
    -JeMROyOXHTz6eEs3zVq
    -JeMRPNOByT5PavObwnS

以下是代码示例:

.controller('RoomCtrl', function($scope, $window, $stateParams, $firebase, $state, Restangular, settings, Auth) {

  $scope.messagesRef = new Firebase('https://xxxxx.firebaseio.com/rooms/' + $stateParams.slug);
  $scope.messagesObj = $firebase($scope.messagesRef.limitToLast(30)).$asArray();
  $scope.current_user = Auth.current_user;

  //Get all the values in order to check if metadata was added 
  $scope.messagesRef.on( "value", function(snapshot) {

    var messages = snapshot.val();

    angular.forEach(messages, function(message, key) {
      // If metada for the current user is not added let's added!
      if( message.translations[$scope.current_user] == undefined){
        $scope.addMetadata(message, key);
      }
    });

  });

  //Add the metadata to very new incoming message
  $scope.messagesRef.on( "child_added", function(snapshot) {

    var message = snapshot.val();
    var key = snapshot.key();

      // If metada for the current user is not added let's added!
    if( message.metadata[$scope.current_user] == undefined){
      $scope.addMetadata(message, key);
    }

    scrollBottom();

  });


  // THE PROBLEM
  $scope.addMetadata = function(message, key){

    $scope.current_user = settings.get("name");

    // Scope messing! 
    $scope.key = key;

    //Calling a metadata api based on my user and the message 
    Restangular.all("/").customGET("metada", {name: $scope.current_user, message: message}).then(function(response){

      // THIS executes defered ( pomises ) 
      // and if i don't mess with the scope i don't realy know the key related to the message I want to modify
      // The problem is that sometimes the KEY here is not the key of the proper message due to the paralell execution of this
      // addMetadata function when iterating on the messagesObj
      var key = $scope.key;

      var metasObj = $scope.messagesRef.child(key).child("metadata").child($scope.current_user);
      metasObj.set(response);

    });

  }


}

0 个答案:

没有答案