Html 当我想在数组中添加元素时,角度问题

Html 当我想在数组中添加元素时,角度问题,html,angular,Html,Angular,我有一个动物阵列。我想在另一个数组中加入每种动物的“尊重”字段 我在EspeeAnimalPresenteTMP中推送所有动物的Espee,然后删除重复项并在EspeeAnimalPresente中保存下一个数组 我有一个角度代码: import { Component, OnInit } from '@angular/core'; import { AnimalService } from "./animal.service"; import { Animal } from "./animal

我有一个动物阵列。我想在另一个数组中加入每种动物的“尊重”字段

我在EspeeAnimalPresenteTMP中推送所有动物的Espee,然后删除重复项并在EspeeAnimalPresente中保存下一个数组

我有一个角度代码:

import { Component, OnInit } from '@angular/core';
import { AnimalService } from "./animal.service";
import { Animal } from "./animal";

@Component({
  selector: 'app-animal',
  templateUrl: './animal.component.html',
  styleUrls: ['./animal.component.css']
})
export class AnimalComponent implements OnInit {

  private animaux:Array<Animal>;
  private especeAnimalPresente:Array<string>;
  private especeAnimalPresenteTmp:Array<string>;
  constructor(private animalService: AnimalService) { }

  ngOnInit() {
    this.recupAllAnimals();
  }

  recupAllAnimals(){
    this.animalService.getAllAnimaux().subscribe(data => {
      this.animaux = data;
      this.recupEspecePresent();
    })

  }

  recupEspecePresent(){
    // if (this.animaux){
      for (let animal of this.animaux) {
          this.especeAnimalPresenteTmp.push(animal.espece);
      }
      this.especeAnimalPresente = this.removeDuplicates(this.especeAnimalPresenteTmp);
    // }
  }

  removeDuplicates(array) {
    let unique = {};
    array.forEach(function(i) {
      if(!unique[i]) {
        unique[i] = true;
      }
    });
    return Object.keys(unique);
  }

}

有人可以帮我吗?

您必须初始化数组,例如在构造函数中:

constructor(private animalService: AnimalService) {
  this.especeAnimalPresenteTmp = [];
}

您需要初始化数组:private-espeeAnimalPresenteTMP:array=[];
constructor(private animalService: AnimalService) {
  this.especeAnimalPresenteTmp = [];
}