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

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

本文关键字:创建 更新 数据 Firebase 何使用 Angular 项目      更新时间:2023-09-26

我想知道在存储到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      
}

也许像这个

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

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  ); 
        }

    }
} ] );