TypeError: error.json is not a function

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

I get this error: enter image description here enter 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 send 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. The answer should always include rxjs functions, but I'm doing it, so I'm not quite sure why I get this error.

Edit:

Thus, the actual problem was not this function, but the missing "/" in front of my route in the main app.js. After that, the problem disappeared.

+5
source share
3 answers

Well, as they say. The error returned from the observable does not contain the json method. This means that it is not a Response type, but it just contains an error. You should just try to print the object in the console and see what is there:

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

You will probably find it as an xmlhttpresponse object

+4
source

Do not catch or collapse. Just handle the exception when you consume a service.

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

Or, if you want to handle an 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 for Observable.throw and how it is used.

The error object you are receiving is invalid. You can add some console logs to see what you get. But it causes problems.

+3
source

Do not call json () for a response of type Response. If you expect the data to return, for example. The client just added, just do:

 .map((data: any) => { return data._embedded.client as Client; }); 
+3
source

Source: https://habr.com/ru/post/1265890/


All Articles