我有从JSON响应过滤数据的问题。我正在使用Google地理编码API并获得响应,我只想重新转发城市名称。城市名称存储在JSON响应中的一个数组中,其中types= "locality", "political"
如何在types=["locality", "political"]
?
这是我的代码:
geocoding.service.ts
getLocation(lat: number, lon: number): Promise<any> {
return this.http.get(this.apiUrl + lat + ',' + lon + '&key' + this.apiKey)
.toPromise()
.then((response) => Promise.resolve(response.json()));
}
geocoding.ts
export class Geocoding {
results: {
address_components: {
long_name: string;
short_name: string;
}
formatted_address: string;
types: {
array: string;
length: number;
}
}
status: string;
}
weather.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { GeocodingService } from '../data/google/geocoding/geocoding.service';
import { Geocoding } from '../data/google/geocoding/geocoding';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.scss']
})
location: Geocoding[];
datasource: Geocoding[];
sortedList: Geocoding[];
ngOnInit() {
this.findLocation2(52.406374, 16.9251681);
}
findLocation2(latitude: number, longtitude: number) {
this.GeoService.getLocation(latitude, longtitude).then(data => {
this.datasource = data;
this.location = this.datasource;
this.sortedList = this.location.filter(
loc => loc.results.types.array === 'locality,political');
});
当我跑步时我得到错误:
EXCEPTION:Uncaught(在promise中):TypeError:_this.location.filter不是函数
答案 0 :(得分:1)
我找到了解决方案! @Ramesh Rajendran和@Sebastian都指出了我正确的方向:
findLocation(latitude: number, longtitude: number) {
return this.GeoService.getData(latitude, longtitude).subscribe(g => {
this.geo = g;
this.GEOARRAY = g.results;
if (isArray(this.GEOARRAY)) {
this.location = this.GEOARRAY.filter(x => x.types[0] === "locality" && x.types[1] === "political");
}
});
}
我创建了GEOARRAY
并指向g.results
(这是数组)。然后我过滤了我想要的东西:)谢谢
答案 1 :(得分:0)
this.location
应该是一个数组。因此,在执行this.location
之前,您需要检查filter
是否为数组。
findLocation2(latitude: number, longtitude: number) {
this.GeoService.getLocation(latitude, longtitude).then(data => {
this.datasource = data;
this.location = this.datasource;
if(Array.isArray(this.location)){
this.sortedList = this.location.filter(
loc => loc.results.types.array === 'locality,political');
});
};