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;
});
}
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)
});
);
}
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);
Note: bindCallback and Observable.create were deprecated,
you could use new Observable instead:
...
return new Observable((subscriber) => {
firebase
.auth()
.onAuthStateChanged((user) => {
subscriber.next(user);
})
}