37

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

gsiradze
  • 4,583
  • 15
  • 64
  • 111
  • 1
    Possible duplicate of [Type 'Observable<{}>' is not assignable to type 'Observable | boolean '](http://stackoverflow.com/questions/38299484/type-observable-is-not-assignable-to-type-observableboolean-boolean) – Roman C Feb 11 '17 at 16:44

3 Answers3

56
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;
    });
  }
Inês Gomes
  • 4,313
  • 1
  • 24
  • 32
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
14

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);
  }
  // ...
}
dhilt
  • 18,707
  • 8
  • 70
  • 85
1

For Angular users with STRICT TYPE setting, all other types seem to work OK (not that I tested ALL types... but number, and custom interfaces for example work without the added type declaration)

Using type boolean, this results in error:

_isBoolean$: BehaviorSubject<boolean> = new BehaviorSubject(false);

change to this:

_isBoolean$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

this works too...

_isBoolean$ = new BehaviorSubject<boolean>(false);
_isBoolean$ = new BehaviorSubject(false);

However, as is quite clear, it removes...the...strict...typing ;)

Joe Code
  • 21
  • 4