Convert Observable<boolean> to a boolean value

Viewed 27628

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?

4 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.

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 don't wanna subscribe, you can get the observable value using async and await, but to do this, you have to converte the Observable into a `Promise.

Something like this:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public loggedin: boolean;
  public otherValue: boolean;

  constructor(private auth: AuthenticationService) { }

  async ngOnInit() {
    this.loggedin = await this.auth.$isLoggedinSource.toPromise();
    this.otherValue = await this.auth.$otherObservable.toPromise();
  }
}

You can see it working in this stackblitz link.

You have to subscribe to observables to get the data.

this.$loggedin.subscribe((data: boolean) => { console.log('am i logged in ', data); }

Related