【问题标题】:firebase onAuth() throwing: TypeError cannot read property 'auth' of undefinedfirebase onAuth() 抛出:TypeError 无法读取未定义的属性“auth”
【发布时间】:2014-12-19 03:32:01
【问题描述】:

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

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

未捕获的类型错误:无法读取未定义的属性 'auth' - firebase-debug.js:9954

这是 firebase 本身的错误还是有人看到我做错了什么? 尝试使用 angular 版本并关闭其他 bower 包,如 angularfire 和 firebase-simple-login,但到目前为止没有成功。

我的身份验证服务代码如下,除了在 .constant 服务上定义我的 url 之外,我没有做任何事情。

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

【问题讨论】:

  • 而不是返回onAuthoffAuth等,当你尝试返回onAuth.bind(ref)等时会发生什么?另外,您的应用中包含哪个版本的 Firebase 网络客户端?
  • @RobDiMarco 我在 1.1.2 上运行,因为它是第一个将登录作为 firebase 核心部分的版本,对吧?但我没有得到你的建议。我要公开的 onAuth 属性将被定义为 var onAuth = ref.onAuth.bind(ref); 是吗?
  • @RobDiMarco 当我像这样onAuth = ref.onAuth.bind(ref) 等离开它时,它工作得很好。但是我在文档中没有找到任何关于此的内容。您能否详细说明这件事作为回应,以便我接受?谢谢!

标签: javascript angularjs authentication firebase


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢! Firebase 支持已发布有用。和你们一起去全栈是一个不错的选择:)
  • 我正要问这样的问题。你不知道这个信息为我节省了多少时间。谢谢
猜你喜欢
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 2018-09-19
  • 2019-09-28
  • 2019-04-05
  • 2021-12-05
相关资源
最近更新 更多