Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

390
Views
TypeError: error.json no es una función

Editar: ¡Lea la parte al final de la pregunta!

me sale este error: ingrese la descripción de la imagen aquíingrese la descripción de la imagen aquí

Mi código de servicio:

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

Y en mi componente tengo esta función de envío:

 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(); }

Hay errores similares aquí y aquí . La respuesta siempre es incluir las funciones rxjs, pero lo hago, así que no estoy muy seguro de por qué recibo este error.

Editar:

Entonces, el problema real no era esta función, sino que faltaba "/" antes de mi ruta en el archivo principal app.js. Después de resolver eso, el problema desapareció.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Bueno, como dice. El error devuelto por el observable no contiene el método json . Esto significa que no es del tipo Response , sino que solo contiene el error. Solo debe intentar imprimir el objeto en su consola y ver qué hay allí:

 .catch((error: any) => console.log(error))

Probablemente encontrará que es solo un objeto xmlhttpresponse

about 4 years ago · Santiago Trujillo Report

0

No atrape y vuelva a lanzar. Simplemente maneje la excepción cuando consuma el servicio.

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

O si desea manejar la excepción en su servicio y solo devolver un error, puede hacer lo siguiente

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

Puede ver la documentación de Observable.throw y cómo se usa.

El objeto de error que está obteniendo tiene un formato incorrecto. Puede agregar algunos registros de la consola para ver lo que está recibiendo. Pero está causando problemas.

about 4 years ago · Santiago Trujillo Report

0

No llame a json() en respuesta de tipo Respuesta. En caso de que espere datos de vuelta, por ej. El cliente acaba de agregar, solo haz:

 .map((data: any) => { return data._embedded.client as Client; });
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!