Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

392
Visualizações
TypeError: error.json is not a function

Edit: Read the part at the end of the question!

I get this error:enter image description hereenter image description here

My service code:

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.

Edit:

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.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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

You will probably find it's just an xmlhttpresponse object

about 4 years ago · Santiago Trujillo Relatório

0

Don't catch and rethrow. Just handle the exception when you consume the service.

 .map(response => response.json());

Or if you want to handle the exception in your service, and just return an error you can do the following

 .map(response => response.json())
            .catch(error => Observable.throw("Error in x service"));

You can see the documentation of Observable.throw and how it is used.

The error object you are getting is malformed. You can add some console logs to see what you are getting back. But it is causing issues.

about 4 years ago · Santiago Trujillo Relatório

0

Dont call json() on response of type Response. In case you expect data back, for eg. Client just added, just do:

.map((data: any) => {
    return data._embedded.client as Client;
});
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda