Angular - res.json()不是函数

Kay*_*Kay 31 angular

我的API服务存在问题.此服务连接到我的nodejs后端api.

错误说

ERROR TypeError: res.json is not a function
Run Code Online (Sandbox Code Playgroud)

我在最近更新此服务后使用HTTPClient而不是Http时收到此错误.我得到这个响应因为我错过了旧的http与新?如果那样的情况是新的响应,我该如何使用它?

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());
  }
}
Run Code Online (Sandbox Code Playgroud)

Max*_*kyi 87

HttpClient.get()适用于res.json()自动和回报Observable<HttpResponse<string>>.您不再需要自己调用此函数.

请参阅角度4中的HTTP和HTTPClient之间的差异?

  • 所以我可以删除整行```.map((res:Response)=> res.json()); ```? (3认同)
  • 这似乎也适用于''Http.post()`,这很有意义。 (2认同)

小智 12

您可以删除以下整行:

 .map((res: Response) => res.json());
Run Code Online (Sandbox Code Playgroud)

根本不需要使用map方法.


小智 10

不需要使用此方法:

 .map((res: Response) => res.json() );
Run Code Online (Sandbox Code Playgroud)

只需使用这种简单的方法代替以前的方法.希望你能得到你的结果:

.map(res => res );
Run Code Online (Sandbox Code Playgroud)

  • 大声笑它工作但但为什么我需要这个命令? (5认同)