使用包含2个或更多类别的对象创建按类别页面

时间:2017-10-01 20:56:59

标签: angular ionic2

我正在为pokedex离子应用构建一个按类型页面。大多数口袋妖怪都有2种类型,因此它们存储在名为" Types"的数组中。我假设我需要遍历口袋妖怪json数据中的类型数组。我不确定我应该如何或在哪里循环

口袋妖怪Json数据

  [
  "Number": "001",
  "Name": "Bulbasaur",
  "Generation": "Generation I",         
  "Types": [
    "Grass",
    "Poison"
           ]
  ]

如果我更改Types数组的格式以匹配Types Json数据的格式,那么它可以正常工作但我丢失了另一种类型。

输入Json数据

[
 {
   "Types": "Grass",

 },
 {
   "Types": "Poison",

 },
]

ByCategory服务

 getPokemonByCategory(Types: string[]): Observable<IPokemon[]> {

    console.log("getPokemonByCategory Service Called")

    return this.getAllPokemon()
        .map((pokemon: IPokemon[]) => pokemon.filter(p => p.Types === Types))
        .do(data => console.log("data object returned from http.get call:"))
        .do(data => console.dir(data))
        //.do(data => console.table(data))
        .catch(this.handleError);
}

ByType组件

import { NavController, NavParams } from 'ionic-angular';
import { Component, OnInit }  from '@angular/core';



import { pokemonService } from '../../services/pokemon.service';
import { IPokemon } from '../../services/pokemon'
import { pokemonDetails } from '../pokemonDetails/pokemonDetails'

@Component({
    selector: 'page-ByType',
    templateUrl: 'ByType.html',
})
export class pokemonByType implements OnInit {
errorMessage: string;
pokemon: IPokemon[];
pokemonType: any;


constructor(private _pokemonService: pokemonService,
    private nav: NavController,
    private navParams: NavParams) {

}

ngOnInit(): void {
    console.log("ngOnInit function called! By Category");

    this.pokemonType = this.navParams.data;
    console.log("Nav" + this.navParams.data)

    this._pokemonService
        .getPokemonByCategory(this.pokemonType.Types)
        .subscribe(
        data => this.extractData(data),
        error => this.errorMessage = <any>error,
    );
}

private extractData(data: any) {

    console.log("extractData function called!");
    console.log("data:")
    console.dir(data);

    this.pokemon = data;

}

}

1 个答案:

答案 0 :(得分:0)

你应该遍历所有类型的口袋妖怪,并检查types数组中的口袋妖怪的索引是否不是-1。

示例:

return this.getAllPokemon()
.map((pokemon: IPokemon[]) => pokemon.filter((p) => {
    p.Types.forEach((type) => {
        return type === type;
    });
}))
.do(data => console.log("data object returned from http.get call:"))
.do(data => console.dir(data))
//.do(data => console.table(data))
.catch(this.handleError);