I trying to catch errors in http post, but it's showing this error:
TypeError: error.json is not a function
I didn't find anything on google.
I followed the example on Angular.io site.
My code:
import {Observable} from 'rxjs/Observable';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
//import 'rxjs/add/operator/catch';
@Injectable()
export class EmpresasCrudService {
constructor(private _http: Http) {
}
// public allItems;
// public _qtd;
postHttpEmpresas(endpoint_url, data): Observable<Response> {
let body = JSON.stringify(data);
let headers = new Headers({'Accept': 'application/json' });
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this._http.post(endpoint_url, body, options)
.map(res => res.json())
.catch(this.handleError);
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
EDIT: when I put:
postHttpEmpresas(endpoint_url, data): Observable<Response> {
let body = JSON.stringify(data);
let headers = new Headers({'Accept': 'application/json' });
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this._http.post(endpoint_url, body, options)
.map(res => res.json())
.catch(err => this.handleError(err));
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
try {
errMsg = error.json();
} catch (e) {
// No content response..
errMsg = null;
}
}
console.log(errMsg);
return Observable.throw(errMsg);
}
it's showing the error in console.log but until give me a error:

