【问题标题】:Angular 5, rxjs map to json, 'json' does not exist on the the type 'objectAngular 5,rxjs 映射到 json,'json' 不存在于类型 'object
【发布时间】:2018-04-17 17:41:01
【问题描述】:

尝试关注在线视频,然后出现,我是 Angular 新手,其他解决方案对我没有帮助。

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

/*
  Generated class for the WeatherProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class WeatherProvider {
  apikey='7d2dc7a226a78c14';
  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() );      
    }
}

【问题讨论】:

    标签: json angular ionic-framework rxjs rxjs5


    【解决方案1】:

    如果您使用新的HttpClient,则无需解析 JSON,因为它会自动为您解码:

    https://angular.io/guide/http#type-checking-the-response

    HttpClient.get() 方法将 JSON 服务器响应解析为匿名 Object 类型。它不知道那个物体的形状是什么。

    还有https://angular.io/guide/http#requesting-non-json-data

    【讨论】:

    • 想不通,请给我看看,我附上了代码,考虑到它可能是任何结果。
    • 您无需致电.json()
    • public getAllTask​​s():Observable { let URI = ${this.serverApi}/tasks/;返回 this.http.get(URI); }
    【解决方案2】:

    使用 angular 5 和httpClient,您不再需要使用地图部分。

    在此处阅读更多信息:https://angular.io/guide/http#type-checking-the-response

    getWeather(city,state){
      return this.http.get(this.url+'/'+state+'/'+city+'.json');     
    }
    

    如果你想获取特定格式的数据,你可以告诉 HttpClient 响应的类型,以便更容易和更明显地消费输出。

    export interface Config {
     heroesUrl: string;
     textfile: string;
    }
    

    然后:

    getConfig() {
      // now returns an Observable of Config
      return this.http.get<Config>(this.configUrl);
    }
    

    【讨论】:

    • 想不通,请给我看看,我附上了代码,考虑到它可能是任何结果。
    • 我已经编辑了答案以展示您应该如何使用 getWeather 函数
    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2018-10-13
    • 2016-05-25
    • 2023-03-17
    • 2018-05-13
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多