AngularJS 服务中的 Firebase AngularFire [英] Firebase's AngularFire in an AngularJS service

查看:28
本文介绍了AngularJS 服务中的 Firebase AngularFire的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 AngularJS 中处理 Firebase 的最佳方式肯定是在服务内部,因此它可供整个应用中的所有控制器使用.

The best way of handling Firebase in AngularJS surely has to be from within a service, so it's available to all Controllers across the App.

我就是无法让它工作!...我第一次尝试使用 angularFire(new Firebase(url)),希望我可以绑定到服务的范围,但 Angular 抱怨它不能 $watch 它.

I just can't get it to work! ... I first tried using angularFire(new Firebase(url)), hoping I could bind to the service's scope, but Angular complains that it cannot $watch it.

所以我像这样尝试了 angularFireCollection:

So I tried angularFireCollection instead like this:

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

然而,angularFireCollection 是一个包含大量方法等的对象.如果我将它绑定到控制器 $scope 上,我只会得到垃圾.它还抱怨在我尝试使用它们之前它无法调用 Firebase 函数(例如 Error: Firebase.push failed: second argument must be a valid function.)...任何人都有任何想法我哪里出错了?

However, the angularFireCollection is an Object containing a load of methods etc. if I bind it to a controller $scope I just get garbage. It also complains that it can't call the Firebase functions before I try to use them (e.g. Error: Firebase.push failed: second argument must be a valid function.)... anyone got any ideas where I'm going wrong?

看到这个PLUNKER

推荐答案

如果要将某些功能封装到服务中,请考虑将返回的 ref 保持在服务的状态.我扩展了你的plunker.它似乎主要做你想要的.

If you want to encapsulate some of the functionality into a service, consider keeping the returned ref in state of the service. I expanded on your plunker. It seems to mostly do what you were trying for.

http://plnkr.co/edit/Uf2fB0

这篇关于AngularJS 服务中的 Firebase AngularFire的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆