You need to enable JavaScript to run this app. 如何在Angular项目中解析MetaWeather API的嵌套JSON天气数据
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular项目中解析MetaWeather API的嵌套JSON天气数据

现有实现的核心问题修正

你目前代码里有4个连续的逻辑错误,导致始终拿不到嵌套结构里的天气数据,逐个对应修正即可:

  • 服务层请求未使用正确的拼接URL
    你定义了带woeid参数的完整URL变量,但实际http.get()时传入的是不带参数的基础地址,请求指向的接口返回内容根本不是目标城市的天气结构
  • 未对响应做字段提取
    服务方法直接返回了完整的接口响应对象,没有通过管道把嵌套在consolidated_weather字段里的数组单独取出
  • 模板层遍历逻辑结构错误
    你在模板里套了两层*ngFor,误以为返回的是嵌套数组,实际即使正确提取了consolidated_weather,它本身就是平铺的一维数组,不需要两层循环
  • Observable未配合async管道使用
    你用rObject$命名表示这是一个流对象,但模板里没有加async管道,Angular不会自动把流的解析值赋给模板变量,最终遍历拿到的是Observable实例本身,而非数组数据

修正后的完整实现

1. 服务层代码修正

首先导入需要的RxJS操作符,将字段提取逻辑放到管道中,保证请求使用正确的带参URL。你已定义的Weather命名空间接口无需修改即可正常使用:

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

@Injectable({ providedIn: 'root' })
export class WeatherService {
  private weatherUrl = 'https://www.metaweather.com/api/location';

  constructor(private http: HttpClient) {}

  /** 返回值直接是提取完成的天气数组流 */
  getWeather(woeid: number): Observable<Weather.ConsolidatedWeather[]> {
    // 使用拼接完成的带参URL发起请求
    const url = `${this.weatherUrl}/${woeid}/`;
    return this.http.get<Weather.RootObject>(url).pipe(
      // 从响应对象中直接提取需要的consolidated_weather数组
      map(response => response.consolidated_weather),
      // 可选错误捕获,和你之前注释的错误处理逻辑对应
      catchError(err => {
        console.error('天气数据加载失败', err);
        return [];
      })
    );
  }
}

注意:你之前注释里的res.json()是Angular 4之前的旧版API写法,现在HttpClient会自动将JSON响应解析为对象,不需要手动调用json方法。

2. 组件层代码修正

将服务返回的Observable直接赋值给组件属性,供模板使用:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { WeatherService } from './weather.service';
import { Weather } from './weather.interface';

@Component({
  selector: 'app-weather-view',
  templateUrl: './weather-view.component.html'
})
export class WeatherViewComponent implements OnInit {
  // 保持命名习惯,rObject$表示这是一个Observable流
  rObject$: Observable<Weather.ConsolidatedWeather[]>;
  private readonly londonWoeid = 44418;

  constructor(private weatherService: WeatherService) {}

  ngOnInit() {
    // 直接将服务返回的流赋值给组件属性,不需要手动subscribe
    this.rObject$ = this.weatherService.getWeather(this.londonWoeid);
  }
}

3. 模板层修正

去掉多余的两层嵌套循环,给Observable加上async管道自动完成订阅/取消订阅的逻辑:

<h2>Weather Forecast {{w}}</h2>
<mat-card>
  <!-- 加async管道自动解析流,直接遍历一维数组即可 -->
  <div *ngFor="let con of rObject$ | async">
    <mat-card-header>
      <h2>Forecast for {{con.applicable_date}}</h2>
    </mat-card-header>
    <mat-card-content>
      Current temperature: {{con.the_temp}}
    </mat-card-content>
  </div>    
</mat-card>

内容的提问来源于stack exchange,提问作者Steve Chacko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.23 18:36:03