Javascript 如何使用Firebase构建Angular项目中的数据创建/更新
我想知道在存储到Firebase时,如何在Angular控制器中构造实际的推送和更新方法。现在我认为有很多重复的代码和糟糕的结构。它看起来像这样:Javascript 如何使用Firebase构建Angular项目中的数据创建/更新,javascript,angularjs,firebase,angularfire,angular-routing,Javascript,Angularjs,Firebase,Angularfire,Angular Routing,我想知道在存储到Firebase时,如何在Angular控制器中构造实际的推送和更新方法。现在我认为有很多重复的代码和糟糕的结构。它看起来像这样: app.controller( "myController", [ "$scope", "$routeParams", function( $scope, $routeParams ) { $scope.id = $routeParams.id; $scope.save = function() { if( $scop
app.controller( "myController", [ "$scope", "$routeParams", function( $scope, $routeParams ) {
$scope.id = $routeParams.id;
$scope.save = function() {
if( $scope.id ) {
// Update
}
else {
// Save
}
}
} ] );
更新和保存之间的唯一区别是使用Firebase存储数据的方法(推送/更新)。否则,存储的对象几乎相同,回调的处理方式也相同。这会产生大量重复的代码。我该如何以一种好的方式构造它以防止重复的代码?可能是这样的
//根据您的评论编辑答案
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 );
}
}
} ] );
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
}
angular.module('app',['firebase','ngRoute']))
.config(应用程序配置)
.constant('FirebaseUrl','谢谢您的输入,但这与Firebase没有太大关系。这是在Firebase中存储数据的方法:var fb=new Firebase(“URL”);fb.push({data},function(){//Callback});或fb.update({data},function(){//Callback});我正在考虑对此使用策略模式。有什么建议吗?我编辑我的答案,查看firebug doc for callback function Example似乎是一个有效的答案。我考虑将其移动到工厂并让它处理:StorageFactory(“URL”)。保存({DATA},function(){//callback});这可能会起作用。真的不需要使用onComplete
回调。本地firebase会先更新fire,这会给它一种快速的感觉,服务器回调会在以后发生。因此,如果你听回调,它可能会变慢。此外,你应该考虑使用AngularFire来简化你的控制器代码。