TypeError:error.json不是函数 [英] TypeError: error.json is not a function
问题描述
阅读问题末尾的部分!
我收到此错误:
我的服务代码:
import { Http, Response, Headers } from "@angular/http";
import { Injectable } from "@angular/core";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from "rxjs";
import { Client } from "./client.model";
@Injectable()
export class ClientService {
private clients: Client[] = [];
constructor(private http: Http){}
addClient(client: Client) {
this.clients.push(client);
const body = JSON.stringify(client);
const headers = new Headers({'Content-Type': 'application/json'});
return this.http.post('http://localhost:3000/client', body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json()));
}
getClients() {
return this.clients;
}
deleteClient(client: Client) {
}
}
在我的组件中,我具有以下提交功能:
And in my component I have this submit function:
onSubmit(form: NgForm) {
let email = form.value.email;
let password = form.value.password;
let firstName = form.value.firstName;
let lastName = form.value.lastName;
const client = new Client(email, password, firstName, lastName);
this.clientService.addClient(client)
.subscribe(
data => console.log(data),
error => console.error(error)
);
form.resetForm();
}
在此处和
There are similar errors here and here. The answer is always to include the rxjs functions, but I do that, so I'm not quite sure, why I get this error.
因此,实际的问题不是此函数,而是主app.js文件中我的路线前缺少"/".解决之后,问题就消失了.
So the actual problem was not this function, but a missing "/" before my route in the main app.js file. After solving that, the issue was gone.
推荐答案
嗯,就像它所说的那样.从observable返回的错误不包含json
方法.这意味着它不是Response
类型,而只是包含错误.您应该只尝试在控制台中打印出对象,然后查看其中的内容:
Well, like it states. The error returned from the observable does not contain the json
method. This means that it is not of the type Response
, but it just contains the error. You should just try to print out the object in your console and see what's in there:
.catch((error: any) => console.log(error))
您可能会发现它只是一个xmlhttpresponse
对象
You will probably find it's just an xmlhttpresponse
object
这篇关于TypeError:error.json不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!