TypeError: error.json is not a function

前端 未结 5 1662
陌清茗
陌清茗 2021-01-04 20:37

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

I get this error:

My service code:

import { Http, Response, Headers } from \         


        
5条回答
  •  情歌与酒
    2021-01-04 21:20

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

提交回复
热议问题