javascript - firebase onAuth() 抛出 : TypeError cannot read property 'auth' of undefined

标签 javascript angularjs authentication firebase

我使用 Firebase 作为我的主要后端解决方案,并创建了一个服务来处理整个应用程序中的身份验证(自从我开始使用 simpleLogin 现在我正在尝试使用他们内置的登录方法,我认为它可能在从应用程序的其余部分访问它之前,最好只将所有内容都设置为作用域)。

我的 firebase 引用工作正常,所以它是 auth 方法。
但是监听方法 onAuth() 和 offAuth() 抛出这个错误:

Uncaught TypeError: Cannot read property 'auth' of undefined - firebase-debug.js:9954

Is this a bug with firebase itself or does anyone see something I'm doing wrong? Tried to play around with angular versions and turning off other bower packages like angularfire and firebase-simple-login but have had no success so far.

My auth service code is as follows and I'm not doing anything beyond defining my url on a .constant service.

    angular.module('myApp')
    .factory('auth', function (firebaseAPIUrl) {

      var ref = new Firebase(firebaseAPIUrl),
          onAuth = ref.onAuth,
          offAuth = ref.offAuth;

      onAuth(function (authData) {
        console.log(authData);
      });

      function getCurrentUser() {
        return ref.getAuth();
      }

      ...

      return {
        onAuth: onAuth,
        offAuth: offAuth,
        getCurrentUser: getCurrentUser,
        ...
      }
    }

最佳答案

在 JavaScript 中,当传递一个函数供以后调用时,请务必注意调用该函数的范围。例如,在定义闭包时,闭包将有自己的作用域,this 可能不再指向我们原来的对象。使用 fn.bind(...) 解决了这个问题。

这可能会变得棘手,因为您正在使用的代码可能取决于特定范围。诀窍是确保在将函数作为参数传递时作用域没有改变,这可以通过在传递之前将方法显式绑定(bind)到原始对象来实现。

查看 http://www.reactive.io/tips/2009/04/28/binding-scope-in-javascript/http://alistapart.com/article/getoutbindingsituations更深入地了解这个主题。

关于javascript - firebase onAuth() 抛出 : TypeError cannot read property 'auth' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26528532/

相关文章:

.net - 当用户密码过期或 "user must change password at next logon"时如何检查AD用户凭据

javascript - Blob 构造函数在 safari/opera 中不起作用?

javascript - 在 Trumbowyg 编辑器中添加新行

javascript - 如何检查字符串在 ";say "的第一个实例之后是否不包含短语 ";say"?

javascript - 为什么 Oranges 和 abc 数组得到相同的输出?

javascript - 如何从服务中将数据检索到指令(angularjs)中

AngularJS 使用 ng-if 与 ng-show

javascript - 用于 Angular MPA 的 Ionic.js 或 Appgyver 类固醇

bash - 如何在 gnome 中记录我的登录/注销和屏幕锁定/解锁

facebook - 如何连接facebook、firebase和flutter?