Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'boolean' is not assignable to type 'Observable<boolean>'

I have that code

method(): Observable<boolean> {
    return this._http.get('sessionId=' + sessionId).map(res=> {
      if (res.status === "success") {
        return true;
      }
      return false;
    });
}

But when sessionId is '' it throws an exception and console logs 401 error

and I add if inside that method:

method(): Observable<boolean> {
    if (sessionId === '')
      return false;
    return this._http.get('sessionId=' + sessionId).map(res=> {
      if (res.status === "success") {
        return true;
      }
      return false;
    });
  }

But now I'm getting an error:

Type 'boolean' is not assignable to type 'Observable'.

How can I solve that?

If I add Observable<boolean> | boolean then I'm getting error that

Property 'map' does not exist on type 'boolean | Observable'.

like image 812
gsiradze Avatar asked Feb 11 '17 16:02

gsiradze


2 Answers

method(): Observable<boolean> {
    if (sessionId === '')
      return false; // <<< obviously not an observable

This should do what you want

import { of, Observable } from 'rxjs';


method(): Observable<boolean> {
    if (sessionId === '')
      return of(false);
    }
    return this._http.get('sessionId=' + sessionId).map(res=> {
      if (res.status === "success") {
        return true;
      }
      return false;
    });
  }
like image 70
Günter Zöchbauer Avatar answered Nov 02 '22 20:11

Günter Zöchbauer


In addition to accepted answer I would add RxJs v6 case where of does not exist on Observable but could be imported directly from rxjs:

import { Observable, of as observableOf } from 'rxjs'; // since RxJs 6

method(): Observable<boolean> {
  if (sessionId === '')
    return observableOf(false);
  }
  // ...
}
like image 21
dhilt Avatar answered Nov 02 '22 20:11

dhilt