Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Observable<boolean> to a boolean value

Tags:

angular

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?

like image 998
Lee9287 Avatar asked Jan 17 '19 13:01

Lee9287


People also ask

How do you return a Boolean observable?

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.

What is observable value?

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() .


2 Answers

There are two ways that you can use to unwrap the value of an Observable.

  1. By using the async pipe in your Template:

    <p>Am I logged In: {{ $isLoggedinSource | async }}</p>

OR

  1. By subscribeing 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();
}

Which one to use?

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.

like image 134
SiddAjmera Avatar answered Sep 18 '22 09:09

SiddAjmera


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.

like image 29
Michael Sandoval Avatar answered Sep 19 '22 09:09

Michael Sandoval