angular触发 $watch() a 属性,而不是整个对象? (火力基地,angular)

angularfire $watch() a property, not the entire object? (firebase, angular)

有没有办法观察对象中的一个 属性 何时发生变化?我试过了

var unwatch = obj.$watch(function() {
  console.log("data changed");
});

当对象中的任何 属性 发生变化时触发。我试过了

var unwatch = obj.myProperty.$watch(function() {
  console.log("data changed");
});

返回错误信息:"TypeError: obj.myProperty.$watch is not a function"。

我试过了

var myTargetValue = $firebaseObject(ref.myProperty);

返回错误消息:"TypeError: Cannot read property 'ref' of undefined"。

您必须为 属性 创建一个 $firebaseObject。但是,使用 Firebase SDK 往往比 $watch().

更有用

JSBin Demo

angular.module('app', ['firebase'])
  .constant('FirebaseUrl', 'https://34474165.firebaseio-demo.com/')
  .service('rootRef', ['FirebaseUrl', Firebase])
  .controller('MyCtrl', MyController);

function MyController($scope, $firebaseObject, rootRef) {
  var objRef = rootRef.child('obj');
  var obj = $firebaseObject(objRef);
  var objMessage = $firebaseObject(rootRef.child('obj/message'));
  
  // watch the whole object
  var unwatch = obj.$watch(function(a) {
    console.log(a);
  });
  
  // watch a child property
  objMessage.$watch(function(a) {
    console.log(a, 'msg');
  });
  
  // get the whole object as it changes
  objRef.on('value', function(snap) {
    console.log(snap.val());
  });
  
  // get the child property as it changes
  objRef.child('message').on('value', function(snap) {
    console.log(snap.val());
  });
}

简答 - 使用 vanilla Firebase(即不使用 Angularfire)

要使用 Angularfire 观看字符串、数字或布尔值 属性,最好使用 vanilla Firebase:

// firebase reference
db = firebase.database().ref().child("myTable");

// watch the property
db.child("someProperty").on("value", function(snapshot) {
  $scope.message = snapshot.val();
});

为什么不 Angular 开火,$value:

使用 $firebaseObject 并传入对原语(字符串、数字、布尔值)的引用 returns 如下所示的对象 (reference documentation):

{
  $id: "myProperty", 
  $priority: null, 
  $resolved: true, 
  $value: "Hi mom!"
}

在此示例中,我要查看的字符串包含在返回对象的 $value 属性 中。我倾向于将 $value 属性 分配给 $scope,但这行不通:

// WONT WORK 
$scope.foo = $firebaseObject(db.child("myProperty")).$value;

Angular 的对象命名约定与 Firebase 的对象命名约定之间存在冲突,这会导致一些问题。根据文档中的 "Important Note",Angular 的 $watch 函数会忽略带有 $ 前缀的属性。换句话说,如果将返回对象的 $value 属性 分配给 $scope,则视图不会更新。

因此,最好只使用 vanilla firebase 来解决这个问题(见上)。希望人们觉得这有帮助。