如何使用Firebase在Angular项目中构建/更新数据

mus*_*se1 2 javascript angularjs firebase angular-routing angularfire

我想知道如何在存储到Firebase时构建Angular控制器中的实际推送和更新方法.目前我认为有很多重复的代码和糟糕的结构.它看起来像这样:

app.controller( "myController", [ "$scope", "$routeParams", function( $scope, $routeParams ) {
    $scope.id = $routeParams.id;
    $scope.save = function() {
        if( $scope.id ) {
            // Update
        }
        else {
            // Save
        }
    }
} ] );
Run Code Online (Sandbox Code Playgroud)

更新和保存之间的唯一区别是用于使用Firebase存储数据的方法(推送/更新).否则,存储的对象几乎相同,并且回调的处理方式相同.这给了很多重复的代码.我如何以良好的方式构建这个以防止重复的代码?

Dav*_*ast 7

使用AngularFire.

AngularFire是官方支持的AngularJS Firebase绑定.它提供了帮助进行同步收集和身份验证的服务.

AngularFire在这里真正可以帮到您的是通过resolve路由器中的对象将同步集合注入控制器.

angular.module('app', ['firebase', 'ngRoute'])
  .config(ApplicationConfig)
  .constant('FirebaseUrl', '<my-firebase-app')
  .service('rootRef', ['FirebaseUrl', Firebase])
  .factory('itemFactory', ItemFactory)
  .controller('MyCtrl', MyCtrl);

function ApplicationConfig($routerProvider) {
  $routeProvider.when('/', {
    templateUrl: 'book.html',
    controller: 'BookController',
    resolve: {
      item: function(itemFactory, $routeParams) {
         // return a promise
         // the resolved data is injected into the controller
         return itemFactory($routeParams.id).$loaded();
      }
    }
  });
}

function ItemFactory(rootRef, $firebaseObject) {
   function ItemFactory(id) {
     var itemRef = rootRef.child('list').child(id);
     return $firebaseObject(itemRef);
   }
}

function MyCtrl($scope, item) {
   $scope.item = item;

   // now you can modify $scope.item and then call $scope.$save()
   // no need to worry whether it's an update or save, no worrying
   // about callbacks or other async data flow      
}
Run Code Online (Sandbox Code Playgroud)