Angular2: res.json is not a function Angular2:res.json 不是一个函数

21 浏览
0 Comments

Angular2: res.json is not a function Angular2:res.json 不是一个函数

我试图在我的代码中使用以下服务:

import {Injectable} from '@angular/core';
import {Http,Response} from "@angular/http";
import 'rxjs/Rx';
@Injectable()
export class HttpService{
    constructor(private http : Http){}
    getData(){
      return  this.http.get("URI")
      .map( (res: Response) => res.json()  );
    }
}

问题是,在运行时它报错:

res.json 不是一个函数

我已经定义了 res 的数据类型为 Response,但仍然报错

.map( (res: Response) => res.json()  ) 

如果我用 subscribe 替换 map,它就能正常工作:

.subscribe( res =>{
                res.json();
                console.log("City is:"+ res.json().city.name)
            });

0
0 Comments

问题出现的原因是在Angular 2中,使用res.json()将响应转换为JSON对象的代码已经过时。在新版的Angular中,HttpClient.get()方法会自动将响应转换为JSON对象并返回Observable<HttpResponse<string>>,所以不再需要手动调用res.json()函数。

解决方法就是将原先的代码中的.map((res: Response) => res.json() ).map(res => res.json())修改为.map(res => res )。这样就可以解决问题。

0
0 Comments

在Angular 5中,如果返回的响应是纯json,可以通过返回res来解决"res.json is not a function"错误。

解决方法:

import { map } from 'rxjs/operators';
...
this.http.get(url)
  .pipe(
    map(res => {
      if (res.status === 200) {
        return res;
      } else {
        throw new Error('Response status is not 200');
      }
    }),
    map(res => res.json())
  )
  .subscribe(data => {
    console.log(data);
  }, error => {
    console.error(error);
  });

或者可以使用toPromise()方法将Observable转换为Promise对象。

解决方法:

import 'rxjs/add/operator/toPromise';
...
this.http.get(url)
  .toPromise()
  .then(res => res.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

这些解决方法可以帮助你解决"res.json is not a function"错误。

0
0 Comments

问题出现的原因是引入的rxjs库版本不兼容。解决方法是使用import 'rxjs/add/operator/map';替代import 'rxjs/Rx';

这个解决方法可以解决问题,但是没有解释为什么和如何解决这个问题。提供这个额外的上下文会显著提高其长期的教育价值。如果我有解释,你难道不认为我会提供吗?几天前我遇到了同样的问题,这就是我解决它的方法。我想不出为什么import 'rxjs/Rx'不起作用,因为Rx.js文件中存在对rxjs/add/operator/map的引用,所以我猜这是某种错误,但我不能百分百确定,所以我没有提到它,只是想提供解决问题的方法。

0