我正在构建一个Angular2应用程序,使用Auth0进行身份验证,使用AngularFire进行数据库。在我的构造函数中,我传递了我的AngularFire af实例,但我无法在回调事件中访问它。有没有其他方法可以访问我的AngularFire实例?
// app/auth.service.ts
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { AngularFire, AuthMethods, AuthProviders } from 'angularfire2';
// Avoid name not found warnings
declare var Auth0Lock: any;
declare var Auth0: any;
@Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock('AUTH0_CLIENT_ID', 'AUTH0_DOMAIN', {});
constructor(private af: AngularFire) {
// Add callback for lock `authenticated` event
this.lock.on("authenticated", (authResult) => {
this.lock.getProfile(authResult.idToken, function(error:any, profile:any){
if(error){
throw new Error(error);
}
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
var options = {
id_token : authResult.idToken,
api : 'firebase',
scope : 'openid name email displayName',
target: 'AUTH0_CLIENT_ID'
};
var auth0 = new Auth0({domain:'AUTH0_DOMAIN', clientID:'AUTH0_CLIENT_ID' });
auth0.getDelegationToken(options, function(err, result){
if(!err){
this.af.auth.login(result.id_token, {
provider: AuthProviders.Custom,
method: AuthMethods.CustomToken
});
console.log(result);
}
});
});
});
}
}
答案 0 :(得分:7)
那是因为你的this
内部回调函数指向该函数。您有三种选择:
let that = this
并在回调中使用that.af
。this
:(error, profile) => {...}
.bindTo(this)
来运行并将其绑定到类另外,我建议使用lambda方法。