This is not a duplicate of this for several reasons. 1. I am using angular 7 not angular 2. 2. I am using rxjs6 not rxjs5. I have no benefit in learning these earlier versions as they are extinct. 3. I am asking about an Observable(boolean) concept when this question does not mention Observable(boolean)
I created an Observable value that I want true/false from it. Here is my code in nav.component.ts file
export class NavComponent implements OnInit {
private $loggedin: Observable<boolean>;
constructor( private auth: AuthenticationService){}
ngOnInit() {
this.$loggedin = this.auth.$isLoggedinSource;
console.log('am i logged in ', this.$loggedin);
}
The console output is :
am i logged in Observable {_isScalar: false, source: BehaviorSubject}
source: BehaviorSubject {_isScalar: false, observers:
Array(0), closed: false, isStopped: false, hasError:
false, …}
_isScalar: false ...
How can I get a boolean, true/false value out of $loggedin?
you first subscribe to getIcons() function, then returns the observableOf(false) and only then, the subscription occurs. don't forget to unsubscribe the observable subscription otherwise you'll have memory leaks.
An ObservableValue is an entity that wraps a value and allows to observe the value for changes. In general this interface should not be implemented directly but one of its sub-interfaces ( ObservableBooleanValue etc.). The value of the ObservableValue can be requested with getValue() .
There are two ways that you can use to unwrap the value of an Observable.
By using the async
pipe in your Template:
<p>Am I logged In: {{ $isLoggedinSource | async }}</p>
OR
subscribe
ing to the Observable in your Component:import { Subscription } from 'rxjs';
...
subscription: Subscription;
...
this.subscription = this.$loggedin
.subscribe(data => console.log('am i logged in ', data));
...
ngOnDestroy() {
this.subscription.unsubscribe();
}
If this $loggedin
Observable is recurring, and you use the Approach 2, then you'll have to assign it to a Subscription
typed property and then call unsubscribe
on it inside the ngOnDestroy
.
With first approach, you aren't really required to do that.
You have to susbscribe to it. Rigth now you are loging the Observable object itself, but what you have to do is subscribe to it so when it is resolved your subscription will listen to it and then print whatever it is resolving.
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