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;
});
}
A callback function is a function passed into another function as an argument which is invoked inside the callee function(here greeting) to complete or after some kind of actions.
Creating Observableslinkimport { Observable } from 'rxjs'; const observable = new Observable(function subscribe(subscriber) { const id = setInterval(() => { subscriber.next('hi'); }, 1000); });
create is deprecated, Instead use new Observable() - Sumit Vekariya - Medium. A custom event service in Angular to subscribe and broadcast messages using observer pattern.
Executing an Observable But the observable function does not emit any values until it is executed. The subscribe() method calls the observable's function that produces and emits data. Thus, subscribing to an observable starts a flow of data between the observable and the observer.
Note: bindCallback
and Observable.create
were deprecated,
you could use new Observable
instead:
...
return new Observable((subscriber) => {
firebase
.auth()
.onAuthStateChanged((user) => {
subscriber.next(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)
});
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With