问题
Ok so I'm pretty new to AngularFire2
and Angular2
in general, I'm learning the authentication method that AngularFire2
provides.
So far I have successfully implemented logging in with Facebook
, my code currently resides in a service
.
So the code is simple (May look disgusting to you), I login via Facebook
retrieve the users access token, and their facebookId, make a call to Facebook graph and retrieve Firstname, Lastname, Gender, Email etc then save this data within Firebase
this is my code for doing the above:
loginWithFacebook(): FirebaseListObservable<string> {
return FirebaseListObservable.create(obs => {
this.af.auth.login({
provider: AuthProviders.Facebook,
method: AuthMethods.Popup,
scope: ['public_profile']
}).then((authState: any) => {
let userRef = this.af.database.object('/users/' + authState.uid); // get user profile
userRef.subscribe(user => {
let url = `https://graph.facebook.com/v2.8/${user.facebookId}?fields=first_name,last_name,gender,email&access_token=${user.accessToken}`;
this.http.get(url).subscribe(response => {
let result = response.json()
userRef.update({
first_name: result.first_name,
last_name: result.last_name,
gender: result.gender,
email_address: result.email,
facebookId: user.facebookId
})
})
})
obs.next(userRef);
}).catch(err => {
obs.throw(err)
});
});
I call this from my login.component
as shown:
loginFacebook() {
this.loginSubscription = this.service.loginWithFacebook().subscribe(data => {
console.log('after finish', data);
});
}
Issue I have is I want to capture if the login with facebook fails or passes I've tried populating the Observable
within the Service method, however when I console.log 'after finish', data I see the following:
Can someone shed any light into how I go about returning true / false from this method? If anyone can see a cleaner way of doing this I would be highly appreciative.
回答1:
Cannot test right now, you could do it like this:
loginWithFacebook(): Observable<boolean> {
return this.af.auth.login({
provider: AuthProviders.Facebook,
method: AuthMethods.Popup,
scope: ['public_profile']
})
.map((authState: any) => {
if (!authState) return false;
let userRef = this.af.database.object('/users/' + authState.uid); // get user profile
userRef.subscribe(user => {
let url = `https://graph.facebook.com/v2.8/${user.facebookId}?fields=first_name,last_name,gender,email&access_token=${user.accessToken}`;
this.http.get(url).subscribe(response => {
let result = response.json();
userRef.update({
first_name: result.first_name,
last_name: result.last_name,
gender: result.gender,
email_address: result.email,
facebookId: user.facebookId
})
})
})
return true;
}).catch(err => {
return Observable.of(false);
});
}
loginFacebook() {
this.loginSubscription = this.service.loginWithFacebook().subscribe(data => {
console.log('after finish', data);
});
}
来源:https://stackoverflow.com/questions/41971144/how-to-return-true-or-false-from-angularfire2-facebook-authentication