[英]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.