问题
I am in an Angular project (6.0) using firebase (5.2). I am using the function:
firebase.auth().onAuthStateChanged
this function returns a firebase.Unsubscribe, which I don't master. I just know to work with Observables, Subjects and Promises.
I would like to use this function as a observable, like, I subscribe to it whenever I get the currentUser back.
So far, I've tried to wrap it a observable:
auth.service.ts
loadUser() {
return Observable.create((observer: Observer<any>) => {
firebase.auth().onAuthStateChanged(
currentUser => { return currentUser }
)
})
}
and I subscribe whenever I start my angular application:
in ngOnInit:
this.authService.loadUser()
.subscribe(
response => {
console.log("response");
console.log(response);
},
error => {
console.log("error");
console.log(error);
}
)
But the subscription is never triggered. I am not wrapping right the function of Firebase. 1. I don't really understand why they return a firebase.unsubscribe. 2. How can I solve the challenge?
Thanks
回答1:
If you consider using the library angularfire2 (I'd really recommend at least trying it out for your application), you can take advantage of injectable services such as AngularFireAuth to track authentication state as an observable. Below is example of using AngularFireAuth from angularfire2 to get current user information, check if a user is logged in, and signin/signout
import { firebase } from '@firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { User, UserCredential } from '@firebase/auth-types';
import { Observable } from 'rxjs';
import { take, map } from 'rxjs/operators';
...
user: Observable<User>;
constructor(private afAuth: AngularFireAuth) {
this.user = this.afAuth.authState;
}
getUser(): Observable<User> {
return this.user.pipe(take(1));
}
isLoggedIn(): Observable<boolean> {
return this.user.pipe(
take(1),
map(authState => !!authState)
);
}
logUser() {
this.getUser().subscribe(user => console.log(user));
}
login(): Promise<UserCredential> {
return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
}
logout() {
return this.afAuth.auth.signOut();
}
Hopefully that helps!
来源:https://stackoverflow.com/questions/51365424/onauthstatechanged-return-unsubscribe-i-want-to-return-currentuser