我试图在http帖子中发现错误,但是它显示了这个错误:
TypeError:error.json不是函数
我在谷歌上找不到任何东西。
我在Angular.io网站上关注了这个例子。
我的代码:
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);
}
编辑: 我放的时候:
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);
}
答案 0 :(得分:0)
如果响应没有正文,则调用Response#json()
将抛出错误(例如,状态204 - 无内容响应)。如果您不知道错误响应是否有正文,那么可以采用以下方式尝试/捕获提取响应内容:
if (error instanceof Response) {
try {
body = error.json();
} catch (e) {
// No content response..
body = null;
}
}