将数组添加到array - typescript中

时间:2017-09-11 16:10:19

标签: angular typescript

我有一个班级:

export class Party {
  constructor ( public title: string,
            public lan1: number,
            public lan2: number ) { }
}

我有服务:

import { Party } from '../classes/party';

export class PartyService {

 parties: Party[] = [];

  addData(title: string, lan1: number, lan2: number) {
    this.parties.push(new Party(title, lan1, lan2));
  }

  getData(): Party[] {
    return this.parties;
   }

}

我有一个组件:

export class AppComponent implements OnInit {
parties: Party[] = [];

title = 'app';

party_location: Location[] =  [
  { lat: 123, lng: 23 }
];

constructor(private partyService: PartyService){}

ngOnInit() {

  this.parties = this.partyService.getData();
 }

}

我想将party属性添加到party_location,如下所示:

  

for(let this in this.parties){         this.party_location.push(new Location(item.lan1,item.lan2));       }

但我不能,因为打字稿没有在item中看到lan1 lan2属性。 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您需要使用for..of来迭代数组。 for..in迭代对象的属性,for..of迭代数组元素:

for (let item of this.parties) { 
   this.party_location.push(new Location(item.lan1, item.lan2)); 
}