[英]Angular 2 filter in JSON response
我在从JSON响应中过滤数据时遇到问题。 我正在使用Google Geocoding 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');
});
当我运行时出现错误:
例外:未捕获(承诺):TypeError:_this.location.filter不是函数
我找到了解决方案! @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
(它是数组)。 然后我过滤了我想要的东西:)谢谢
this.location
应该是一个数组。 因此,在执行filter
之前,需要检查this.location
是否为数组。
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');
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.