我使用 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/