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'.
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 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);
}
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With