9

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.

4
  • Possible duplicate of Angular2: res.json is not a function Commented Mar 24, 2017 at 20:31
  • @Igor You read my hole question, didn't you? I pointed out, that there are similar issue, which don't seem to work for me.. Commented Mar 24, 2017 at 20:33
  • I did read your whole question. The reason is because it does not contain json just like in the duplicate. There are other similar questions all with the same culprit. Debug in your browser and check out the state of the response in the error, you will probably find that there is indeed no json available. You can also do this by checking out the result in the network IO tab of your browsers debugger. Commented Mar 24, 2017 at 20:35
  • However if you wanted to prove those possible duplicates had no relation you should have done this already and copied that data into your question. As of now this (the duplicate) is most likely the culprit as far as we (anyone not sitting in front of your PC) can see. Commented Mar 24, 2017 at 20:37

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

8 Comments

@Zoker try the solution I just added.
try now, I just realized you shouldn't be catching anything there you will catch on the method that calls the service.
Are you sure? In the docs, they do map and catch: angular.io/docs/ts/latest/guide/…
@Zoker I usually dont it this way. But maybe it is best practice. I think the solution I provided should work now.
@Eudardo: Now I get this error: fs5.directupload.net/images/170324/umeqvh24.png
|
3

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

Comments

0

Just Make Changes into your app.module.ts file

import { HttpModule} from "@angular/http";

@NgModule({

declarations: [

---- ],
imports: [ BrowserModule, HttpModule],

providers: [
    DataService
],   
bootstrap: [
   AppComponent
]})

This will fix your issue now in updated version of angular the methods are rewritten.

Comments

0

If it can help someone, I have got the same error when trying to parse API error response and notify the user.

When using the new HttpClient class, response.json() or error.json() are not needed. When used you will have that type of error :

Property 'json' does not exist on type 'HttpErrorResponse'

For example the service code above should look like:

import { HttpClient, HttpResponseBase, HttpErrorResponse } from '@angular/common/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: HttpResponseBase) => response)
        .catch((error: HttpErrorResponse ) => Observable.throw(error));
  }

  getClients() {
    return this.clients;
  }

  deleteClient(client: Client) {

  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.