问题
I have an auth guard that needs an asynchronous response true/false when the site is visited and the user is already logged in.
I'm using Firebase's onAuthStateChanged
(link to docs) and it uses a callback function. How can I turn my isLoggedIn()
method into something that can return Observable<boolean>
?
Typscript:
get isLoggedIn(): Observable<boolean> {
// want something like this:
return Observable.fromCallback(firebase.auth().onAuthStateChanged).map(user => !!user);
// this returns () => boolean, but I need a promise or observable
return firebase
.auth()
.onAuthStateChanged((user) => {
return !!user;
});
}
回答1:
You can do it like this.
get isLoggedIn(): Observable<boolean> {
// want something like this:
return Observable.create(
observer => firebase
.auth()
.onAuthStateChanged((user) => {
observer.next(!!user)
});
);
}
回答2:
there is one more way of doing this using bindCallback from rxjs/observable/bindCallback
const observable=bindCallback(functionWhichExpectsCallBack)
e.g
function foo(value, callback) {
callback(value);
}
//converts callback to observable
const observable = bindCallback(foo);
observable(1)
.subscribe(console.log);
来源:https://stackoverflow.com/questions/43131162/making-an-observable-from-a-callback