繁体   English   中英

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

[英]How to structure creating/updating data in Angular project with Firebase

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

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

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

使用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      
}

也许是这样的

//根据您的评论编辑EDIT答案

app.controller( "myController", [ "$scope", "$routeParams", function( $scope, $routeParams ) {
    $scope.id = $routeParams.id;
    $scope.save = function() {

        //  https://www.firebase.com/docs/web/api/firebase/update.html
        // message when the data has finished synchronizing.
        var onComplete = function(error) {
          if (error) {
            console.log('Synchronization failed');
          } else {
            console.log('Synchronization succeeded');
          }
        };



        var fb = new Firebase( "URL" ); 
        if( $scope.id ) {
            // Update
            fb.update( { DATA }, onComplete  ); 
        }else{
            fb.push( { DATA }, onComplete  ); 
        }


    }
} ] );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM