我正在创建一个角度认证服务。 我有一个带有公用变量的服务(我需要公用,因为我在许多组件中都使用了它),它是已登录的用户,我想在登录/注销后更新此变量。
@Injectable()
export class AuthService implements OnInit{
public loggedUser: firebase.User;
constructor(private firebaseAuth: AngularFireAuth) {
this.loggedUser = firebase.auth().currentUser;
} ....
我具有服务中的所有功能:
signup(email: string, password: string) {
this.firebaseAuth
.auth
.createUserWithEmailAndPassword(email, password)
.then(value => {
console.log('Success!', value);
this.loggedUser = firebase.auth().currentUser;
})
.catch(err => {
console.warn('Something went wrong:',err.message);
});
}
login(email: string, password: string) {
this.firebaseAuth
.auth
.signInWithEmailAndPassword(email, password)
.then(value => {
console.log('Nice, it worked!');
this.loggedUser = firebase.auth().currentUser;
})
.catch(err => {
console.warn('Something went wrong:',err.message);
});
}
,他们工作顺利。但是使用facebook auth:
facebooklogin(){
var provider = new firebase.auth.FacebookAuthProvider();
this.firebaseAuth
.auth
.signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = (<any> result).credential.accessToken;
// The signed-in user info.
var userResult = result.user;
this.loggedUser = firebase.auth().currentUser;
console.log(userResult,token)
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
console.warn(errorCode,errorMessage,email,credential)
});
}
将currentUser分配给loggingUser时出现错误:“无法设置未定义的属性'loggedUser'”。因此,就像它未被识别一样。如果我用console.log记录,则实际上是不确定的。怎么样?
答案 0 :(得分:1)
为此,您应该使用箭头功能,类似于之前的2个功能
facebooklogin(){
var provider = new firebase.auth.FacebookAuthProvider();
this.firebaseAuth
.auth
.signInWithPopup(provider).then(result => {
}).catch(error =>{
});
}
或者如果您希望以相同的方式进行操作,请先在回调外部定义一个变量self,然后在回调中引用self
facebooklogin(){
var self = this
var provider = new firebase.auth.FacebookAuthProvider();
this.firebaseAuth
.auth
.signInWithPopup(provider).then(function(result) {
//self.loggedin
}).catch(function(error) {
});
}