stu*_*edy 8 angularjs firebase angularjs-service angularfire
在AngularJS中处理Firebase的最佳方式肯定必须来自服务,因此它可供整个应用程序中的所有控制器使用.
我只是无法让它工作!...我第一次尝试使用angularFire(new Firebase(url)),希望我可以绑定到服务的范围,但Angular抱怨它不能$watch.
所以我尝试使用angularFireCollection,如下所示:
app.factory('myService', function myService(angularFireCollection) {
var url = 'https://myfirebase.firebaseio.com';
return {
getAll: function(path) {
var ref = angularFireCollection(new Firebase(url + '/' + path));
console.log(ref);
return ref;
},
...
};
});
Run Code Online (Sandbox Code Playgroud)
但是,angularFireCollection是一个包含大量方法等的Object,如果我将它绑定到控制器$ scope我只是得到垃圾.它还抱怨它在我尝试使用之前无法调用Firebase功能(例如Error: Firebase.push failed: second argument must be a valid function.)......任何人都有任何想法我会出错?
看到这个PLUNKER
杰夫正确地回答了这个问题......我只是在杰夫的例子中为那些感兴趣的人发布了一个进一步的发展.
我已经抽象了Firebase服务创建,因此您可以动态创建所需Firebase服务的实例: -
var registerFirebaseService = function (serviceName) {
app.factory(serviceName, function (angularFire) {
var _url = null;
var _ref = null;
return {
init: function (url) {
_url = url;
_ref = new Firebase(_url);
},
setToScope: function (scope, localScopeVarName) {
angularFire(_ref, scope, localScopeVarName);
}
};
});
};
Run Code Online (Sandbox Code Playgroud)
您首先按如下方式创建服务实例
registerFirebaseService('itemsService'); // create itemsService instance
Run Code Online (Sandbox Code Playgroud)
然后,您可以将itemsService服务注入控制器.该实例使用您的Firebase网址初始化,例如
itemsService.init('https://firebase.firebaseio.com/' + userId + '/items');
Run Code Online (Sandbox Code Playgroud)
Firebase现在可以绑定到您的控制器,例如
itemsService.setToScope($scope, 'items');
Run Code Online (Sandbox Code Playgroud)
适应PLUNKER
| 归档时间: |
|
| 查看次数: |
8495 次 |
| 最近记录: |