Angular - res.json () n'est pas une fonction
Je rencontre un problème avec mon API de Service. Ce service se connecte à mon nodejs api principale.
Le message d'erreur indique
ERROR TypeError: res.json is not a function
J'obtiens cette erreur après avoir récemment mis à jour ce service pour utiliser le HTTPClient au lieu de Http. Im obtenir cette reponse parce que je manque le vieux http avec le nouveau? si c'est le cas, est-il une nouvelle Réponse et comment puis-je l'utiliser?
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
@Injectable()
export class ApiService {
constructor(
private http: HttpClient,
private jwtService: JwtService
) {}
private setHeaders(): HttpHeaders {
const headersConfig = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (this.jwtService.getToken()) {
headersConfig['Authorization'] = this.jwtService.getToken();
}
return new HttpHeaders(headersConfig);
}
private formatErrors(error: any) {
return Observable.throw(error.json());
}
get(path: string, httpParams: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), params: httpParams })
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
put(path: string, body: Object = {}): Observable<any> {
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
body,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
delete(path): Observable<any> {
return this.http.delete(
`${environment.api_url}${path}`,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
}
source d'informationauteur KHAN
Vous devez vous connecter pour publier un commentaire.
HttpClient.get()
s'appliqueres.json()
automatiquement et renvoieObservable<HttpResponse<string>>
. Vous n'avez plus besoin d'appeler cette fonction vous-même.Voir Différence entre HTTP et HTTPClient angulaire 4?
N'avez pas besoin d'utiliser cette méthode:
Il suffit d'utiliser cette méthode simple au lieu de la méthode précédente. j'espère que vous aurez votre résultat:
Vous pouvez supprimer la totalité de la ligne ci-dessous:
Pas besoin d'utiliser la méthode map.