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

gsiradze picture gsiradze · Feb 11, 2017 · Viewed 60.5k times · Source

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

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Feb 11, 2017
method(): Observable<boolean> {
    if (sessionId === '')
      return false; // <<< obviously not an observable

This should do what you want

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