读取/下载JSON文件并通过角度5

时间:2018-05-24 16:24:25

标签: html json typescript angular5 openweathermap

我正在尝试从openweathermap读出JSON文件,并在角度为5的帮助下将其存储在本地JSON文件中。但由于我未知的原因,我在浏览器检查器中收到以下消息:

core.js:1448 ERROR Error: Error trying to diff 'Rotterdam'. Only arrays and iterables are allowed

不确定这究竟意味着什么,并试图谷歌问题确实找到了我的解决方案。此外,当我调试它看起来它可以正确地从openweathermap读取JSON,但我感觉,当我尝试订阅我的本地JSON我做错了。

以下是该服务的代码:

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';

import { City } from '../_models/city.model';
import { Search } from '../_models/search.model';
import { variable } from '@angular/compiler/src/output/output_ast';

const API_URL_SEARCH = 'http://localhost:3000/search';
const API_ARGS: RequestOptions = new RequestOptions();
const headers = new Headers();
headers.append('Content-Type', 'application/json');
API_ARGS.headers = headers;

@Injectable()
export class CityService {
  searchList: Search[];
  private searchURL = 'http://openweathermap.org/data/2.5/weather?q=rotterdam&appid=b6907d289e10d714a6e88b30761fae22';
  constructor(private http: Http) { }

  getOpenWeatherMap(): Observable<Search[]> {
    return this.http.get(this.searchURL)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

  private extractData(res: Response) {
    const body = res.json();
    return body;
  }

  private handleError(error: Response | any) {
    console.error(error.message || error);
    return Observable.throw(error.message || error);
  }
 }

组件的代码:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { CityService } from '../_shared/city.service';
import { Search } from '../_models/search.model';


@Component({
  selector: 'app-city',
  templateUrl: './city.component.html',
  styleUrls: ['./city.component.css']
})
export class CityComponent implements OnInit {

  searches: Observable<Search[]>;
  searchList: Search[];
  errorMessage: String;
  constructor(private cityService: CityService) { }

  ngOnInit() {
    this.searches = this.cityService.getSearches();
  }

  getOpenWeatherMap() {
    // this.cityService.getOpenWeatherMap()
    //                 .subscribe(result => this.searches = this.cityService.getOpenWeatherMap());
    this.searches = this.cityService.getOpenWeatherMap();
    this.searches.subscribe(
      searchList => this.searchList = searchList,
      error => this.errorMessage = <any>error
    );
  }
}

模型的代码:

export class Search {
  constructor(
      public coord: Coord,
      public weather: Weather,
      public base: string,
      public main: Main,
      public visability: string,
      public wind: Wind,
      public clouds: Clouds,
      public dt: string,
      public sys: Sys,
      public id: string,
      public name: string,
      public cod: string
  ) {}
}

export class Coord {
  constructor(
      public lon: string,
      public lat: string
  ) {}
}

export class Weather {
  constructor(
    public id: string,
    public main: string,
    public description: string,
    public icon: string
  ) {}
}

export class Main {
  constructor(
    public temp: string,
    public pressure: string,
    public sea_level: string,
    public humidity: string,
    public temp_min: string,
    public temp_max: string
  ) {}
}

export class Wind {
  constructor(
    public speed: string,
    public deg: string
  ) {}
}

export class Clouds {
  constructor(
    public all: string
  ) {}
}

export class Sys {
  constructor(
    public type: string,
    public message: string,
    public country: string,
    public sunrise: string,
    public sunset: string
  ) {}
}

HTML代码如下:

<div class = "container">
  <h2>Search for city</h2>

    <form>
        <div class = "row" >
          <div class="col-sm-12">
      <label for="cityField">City Name:</label>
      <input class="cityField" #cityField>
      <button class="btn btn-primary" (click)="getOpenWeatherMap()">Search</button>
    </div>
    </div>
    </form>

    <div *ngIf="errorMessage"> {{errorMessage}} </div>

    <div class="container">
      <h2>Search</h2>
      <table class="table" style="width:100%">
        <tr>
            <th>City Name</th>
            <th>Country</th>
            <th>weather</th>
            <th>Temp (°C)</th>
            <th></th>
          </tr>
          <tr *ngFor="let Search of searches | async">
              <td>{{Search.name}}</td>
              <td>{{Search.sys.country}}</td>
              <td>{{Search.weather[0].description}}</td>
              <td>{{Search.main.temp}}</td>
              <td><button class="btn btn-danger" (click)="deleteCity(Search)">Delete</button></td>
            </tr>
      </table>
  </div>   
</div>

任何帮助都将受到高度赞赏。顺便说一句,我刚开始有角度所以请记住我不是那么熟练。

1 个答案:

答案 0 :(得分:0)

经过多次调查后,我发现确切的问题在哪里。正如错误陈述所述,它只能处理数组和迭代。所以我们得出结论只是制作一个完整的JSON数组。

所以在服务中:

private extractData(res: Response) {
   const body = res.json();
   return body;
}

这必须成为:

private extractData(res: Response) {
   const body = Array.of(res.json());
   return body;
}

这修复了错误,我可以正确读出JSON并将参数复制到本地JSON文件。