JSON响应中的Angular 2过滤器

时间:2018-04-18 07:00:44

标签: json angular typescript

我有从JSON响应过滤数据的问题。我正在使用Google地理编码API并获得响应,我只想重新转发城市名称。城市名称存储在JSON响应中的一个数组中,其中types= "locality", "political"

JSON response

如何在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不是函数

2 个答案:

答案 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');
    });
};
相关问题