如何提取JSON数据并加载到Angular 7中的数组中

时间:2019-04-08 18:17:04

标签: json angular typescript angular7

我有一个包含一些数据的本地JSON文件。我只想从中提取CityCodes并存储在Array中。然后我想将CityCodes发送到OpenWeatherMap API Request。最后要在HTML文件中显示所有的天气记录。

CityData.json:

{
    "List": [
    {
    "CityCode": "1248991",
    "CityName": "Colombo",
    "Temp": "33.0",
    "Status": "Clouds"
    },
    {
    "CityCode": "1850147",
    "CityName": "Tokyo",
    "Temp": "8.6",
    "Status": "Clear"
    },
    {
    "CityCode": "2644210",
    "CityName": "Liverpool",
    "Temp": "16.5",
    "Status": "Rain"
    }
]

Weather.Service.ts:

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

@Injectable({
  providedIn: 'root'
})
export class WeatherService {

  apiKey = '9402da6bd74c395f71604c624cc2b231';
  url;

  constructor(private http:HttpClient) { 
    this.url='http://api.openweathermap.org/data/2.5/group?id=';  //API GET URL

  }

  getWeather(cityCode){
    return this.http.get(this.url+cityCode+'&units=metric&appid='+this.apiKey);
  }

}

home.component.ts:

我在这里手动传递区号。取而代之的是,我需要在此处通过JSON发送区号。

import { Component, OnInit } from '@angular/core';
import { WeatherService } from "../shared/weather.service";
// import { weather} from "../shared/weather.model";

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

  location={    
    code: '1248991'  //Passing Area Code Manually
  };

  public weather: any;

  constructor(private weatherService:WeatherService) {

  }

  ngOnInit() {
    this.weatherService.getWeather(this.location.code).subscribe((Response:any)=>{
      console.log(Response);
      this.weather = Response.list;
    })
  }

}

home.component.html:

<table class="table table-hover">
          <thead>
            <th>City</th>
            <th>City Code</th>
            <th>Temperature</th>
            <th>Description</th>            
          </thead>
          <tbody>
            <tr *ngFor="let weather of weather">
              <td>{{weather.name}}</td>
              <td>{{weather.id}}</td>
              <td>{{weather.main.temp}}</td>
              <td>{{weather.weather[0].description}}</td>              
            </tr>
          </tbody>
        </table>

3 个答案:

答案 0 :(得分:1)

我通过将JSON响应放入一个数组来解决它。

Home.component.ts

  public data: any;
  public weather: any;

  constructor(private weatherService:WeatherService) {

  }

  ngOnInit() {   
    this.weatherService.getJsonData('./assets/City.json').subscribe(data => {
            this.data = data;         //Reading JSON Data
            this.getWeatherList();    //Calling GetWeatherList Function
      }); 
  }

  getWeatherList(){
    if (this.data) {

      // console.log(this.data);

      const dataList = this.data.List;
      let tempArr : any = [];

      for (let temp of dataList) {
        this.weatherService.getWeather(temp.CityCode).subscribe((Response: any) => {
          tempArr.push(Response.list[0]);         //Pushing Response to Array
        })        
      }
      console.log(tempArr)
      this.weather = tempArr;   //Assigning Array to Weather Constant
    }
  }

答案 1 :(得分:0)

首先使用HTTP获取JSON,然后使用forJoin从API读取并行(如Promise.all)天气数据。

// add in service
get(url){
    return this.http.get(url);
}

//component
ngOnInit() {
    this.weatherService.get('json file url').subscribe((cities:any)=>{
        const {List} = cities;
        const obsArr = List.map(location => this.weatherService.getWeather(location.CityCode))
        forkJoin(obsArr).subscribe(  => { // import forkJoin
            console.log(val)
            this.weatherlist = val; // modify according to response
        }); 
    })
  }

//html
<tr *ngFor="let weather of weatherlist">
    <td>{{weather.name}}</td>
    <td>{{weather.id}}</td>
    <td>{{weather.main.temp}}</td>
    <td>{{weather.description}}</td>              
</tr>

答案 2 :(得分:0)

更新气象服务以获取本地JSON文件路径并读取内容,

  public getJsonData(filePath: string){
        return this.http.get(filePath);
  }

在您的组件中执行以下操作,

  export class HomeComponent implements OnInit {

  public data: any;
  public weather: any;

  constructor(private weatherService: WeatherService) {}

  ngOnInit() {   
    this.weatherServiceget.getJsonData(./data.json).subscribe(data => {
            this.data = data;
            this.getWeatherList();
      }); 
  }

  getWeatherList(){
    if (this.data) {
      const dataList = JSON.parse(this.data).List;
      for (let temp of dataList) {
        this.weatherService.getWeather(temp.CityCode).subscribe((Response: any) => {
          console.log(Response);
          if (Response && Response.list) {
            this.weather.push(Response.list[0]);
          }
        })
      }
    }
  }
}

这是一个有效的示例,无法读取stackblitz上的文件数据,因此对其进行了硬编码。 Example