如何使用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
}
也许像这个
//编辑根据您的评论编辑的答案
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 );
}
}
} ] );
相关文章:
- 如何为动态创建的文本区域中输入的值更新ng模型
- Knockout映射创建/更新出现问题
- 创建新对象时,为什么要更新旧对象
- 如何创建对表单的自我更新响应
- 在文本输入区域中创建双向更新
- 基本D3.js:创建或更新元素
- 如何创建独立于数组更新的组件列表
- 确定是创建新对象还是更新现有对象
- 更新脚本以针对具有递增 ID 的新创建的表行运行
- 如何使用AJAX创建/更新单选按钮
- 如何使用输入复选框创建/更新数组
- 如何在 D3JS 中创建更新函数
- 在 Jquery - jTable 中创建/更新模式的字段末尾添加自定义按钮,如提交按钮
- 在创建/更新时,使用$state.go('main.myEntries'),但直到重新加载更新或新内容为
- 如何使用Firebase在Angular项目中构造创建/更新数据
- 如何根据骨干模型的响应创建/更新骨干视图
- 创建更新请求对象的Express参数中间件
- BackboneJS使用不同的URL保存模型(创建/更新)
- 如何创建更新模型的按钮's属性
- Sencha Touch:用于创建/更新功能的ScriptTagProxy url