You need to enable JavaScript to run this app. 如何从API GET请求返回的数组中提取指定属性匹配自定义TypeScript interface
优惠活动
大模型
产品
解决方案
定价
更多

如何从API GET请求返回的数组中提取指定属性匹配自定义TypeScript interface

问题核心原因

你遇到的问题有两个核心点:

  1. AccuWeather的城市搜索接口返回的是数组结构,你目前直接把它当成单个citySearch对象处理,类型不匹配
  2. 你定义的citySearch接口里属性名是LocalizeName,API返回的对应属性名是LocalizedName(多了一个d),拼写不一致会导致属性匹配失败

具体修改方案

第一步:修改WeatherService代码

调整请求类型声明,在map操作符中完成属性映射:

import {citySearch} from '../interfaces/citySearch.model'
// 未导入操作符的话需要补一下导入
import { map, catchError } from 'rxjs/operators';
import { of, Observable } from 'rxjs';

// 可选:定义API原始返回的类型,提升类型安全性,不想定义可以直接用any[]代替
interface RawCityResult {
  Key: string;
  LocalizedName: string;
  Country: {
    LocalizedName: string;
  }
}

export class WeatherService {
  private apikey = '你的实际apikey'; // 记得补全你的apikey配置

  constructor(public http: HttpClient) { }

  getLocation(query:String):Observable<citySearch>{
    return this.http.get<RawCityResult[]>(`http://dataservice.accuweather.com/locations/v1/cities/autocomplete?apikey=${this.apikey}&q=${query}&language=en-us`)
    .pipe(
      map((receivedList: RawCityResult[])=>{
        // 取第一个匹配度最高的结果,如果你需要返回所有匹配结果,可以改成遍历整个数组返回citySearch[]
        const firstResult = receivedList[0];
        if(!firstResult) throw new Error('未找到匹配城市');
        // 按照你定义的interface结构做属性映射
        return {
          Key: firstResult.Key,
          LocalizeName: firstResult.LocalizedName,
          Country: {
            LocalizeName: firstResult.Country.LocalizedName
          }
        } as citySearch
      }),
      // 可选:添加错误处理
      catchError(err => {
        console.error('城市搜索失败', err);
        throw err;
      })
    )
  }
}

第二步:可选修改Component代码(添加错误处理)

export class TestComponent implements OnInit {
  citySearch!: citySearch;

  constructor(public weatherService:WeatherService) { }

  ngOnInit(): void {
    this.weatherService.getLocation("tel aviv").subscribe({
      next: (data:citySearch)=>{
        this.citySearch = data
        console.log("this.citySearch:", this.citySearch);
      },
      error: (err) => {
        console.error('获取城市信息失败', err);
      }
    })
  }
}

扩展说明

如果你需要返回所有搜索匹配的城市列表,只需要做两处调整:

  1. 把getLocation的返回值类型改为Observable<citySearch[]>
  2. map操作符里改成遍历整个数组:
map((receivedList: RawCityResult[])=>{
  return receivedList.map(item => ({
    Key: item.Key,
    LocalizeName: item.LocalizedName,
    Country: {
      LocalizeName: item.Country.LocalizedName
    }
  })) as citySearch[]
})

然后Component里的citySearch类型也要对应改为citySearch[]即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 20:36:01