首页 > 解决方案 > 连接api时出现ionic 3 HttpClient错误,“对象”类型上不存在属性“json”

问题描述


我正在使用 Ionic 3,我正在尝试连接到 api,我的代码如下所示。

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map'

@Injectable()
export class WeatherProvider {
  apikey = 'xxxxxxxxxxxxxxx';
  url;
  constructor(public http: HttpClient) {
    console.log('Hello WeatherProvider Provider');
    this.url= 'http://api.wunderground.com/api/'+this.apikey+'/conditions/q';
  }
  getWeather(city, state){
    return this.http.get(this.url+'/'+state+'/'+city+'.json')
      .map(res => res.json());
  }
}

我知道错误,就是这段代码 .map(res => res.json());

这是错误日志

Typescript 错误属性“json”在“对象”类型上不存在。

src/providers/weather/weather.ts
  return this.http.get(this.url+'/'+state+'/'+city+'.json')
    .map(res => res.json());
}

离子框架:3.9.2 离子应用脚本:3.1.9 Angular 核心:5.2.10 Angular 编译器 CLI:5.2.10 节点:9.2.1 操作系统平台:Linux 4.13 导航器平台:Linux x86_64 用户代理:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36

请给我一个解决方案

标签: htmlangularionic3

解决方案


您不需要调用.json()withhttpClient因为默认情况下响应是 JSON

return this.http.get(this.url+'/'+state+'/'+city+'.json')
    .map(res => res);

推荐阅读