I am working on an Angular app in which I am making a rest call through HTTP as below:
login(email, password) {
let headers = new Headers();
headers.a
with rxjs 6
import { throwError } from 'rxjs';
throwError('hello');
if (response.success == 0) {
throw Observable.throw(response);
}
Edit for rxjs 6:
if (response.success == 0) {
throw throwError(response);
}
rxjs 6
import { throwError } from 'rxjs';
if (response.success == 0) {
return throwError(response);
}
rxjs 5
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
if (response.success == 0) {
return new ErrorObservable(response);
}
What you return with ErrorObservable
is up to you
Here is the official example (that emits number 7 and then error 'oops!'):
import { throwError, concat, of } from 'rxjs';
const result = concat(of(7), throwError(new Error('oops!')));
result.subscribe(x => console.log(x), e => console.error(e));
From: https://rxjs-dev.firebaseapp.com/api/index/function/throwError
Use the catch operator
this.calcSub = this.http.post(this.constants.userUrl + "UpdateCalculation", body, { headers: headers })
.map((response: Response) => {
var result = <DataResponseObject>response.json();
return result;
})
.catch(this.handleError)
.subscribe(
dro => this.dro = dro,
() => this.completeAddCalculation()
);
And handle the error like this:
private handleError(error: Response) {
console.error(error); // log to console instead
return Observable.throw(error.json().error || 'Server Error');
}
Most of my issues were related to the imports, so here's the code that worked for me...
import {_throw} from 'rxjs/observable/throw';
login(email, password) {
...
return this.http.post(`${this._configService.getBaseUrl()}/login`, body, options)
.map((res: any) => {
...
if (response.success == 0) {
_throw(response);
} else if (response.success == 1) {
...
}
});
}
This will be the solution if you are facing errors like...
ERROR TypeError: WEBPACK_IMPORTED_MODULE_2_rxjs_Observable.Observable.throw is not a function