TypeError:error.json不是函数

Zok*_*ker 8 angular

编辑:阅读问题末尾的部分!

我收到此错误:在此输入图像描述在此输入图像描述

我的服务代码:

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) {

    }
}
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我有这个提交功能:

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();
}
Run Code Online (Sandbox Code Playgroud)

这里这里也有类似的错误.答案总是要包含rxjs函数,但我这样做,所以我不太确定,为什么我会得到这个错误.

编辑:

所以实际问题不是这个函数,而是在app.js主文件中我的路径之前缺少"/".解决之后,问题就消失了.

Pie*_*Duc 6

好吧,就像它说的那样.从observable返回的错误不包含该json方法.这意味着它不是类型Response,但它只包含错误.您应该尝试在控制台中打印出对象并查看其中的内容:

.catch((error: any) => console.log(error))
Run Code Online (Sandbox Code Playgroud)

您可能会发现它只是一个xmlhttpresponse对象


Edu*_*nis 5

不要抓住并重新抛出.只需在使用服务时处理异常.

 .map(response => response.json());
Run Code Online (Sandbox Code Playgroud)

或者,如果要在服务中处理异常,只返回错误,则可以执行以下操作

 .map(response => response.json())
            .catch(error => Observable.throw("Error in x service"));
Run Code Online (Sandbox Code Playgroud)

您可以看到Observable.throw 的文档及其使用方法.

您获得的错误对象格式不正确.您可以添加一些控制台日志以查看您要返回的内容.但它引起了问题.