推送到接口类型的数组

时间:2018-03-08 13:37:56

标签: angular typescript

我有一个名为TestEvent类型的行的数组,并且想要推送到数组,我不能输出对象我推它只显示未定义 正如你可以看到this.rows显示数组,但是当我尝试输出一个特殊数组this.rows [0]时,我得到了未定义。 (Typescript 2.7,Angular 5)

我尝试过以下指南:

import { TestEvent } from '../../models/event'
rows: TestEvent[] = []

public push(){
    var test: TestEvent = {id: '222', category:'testcat', event_name: 'name'}
    console.log(test) // Outputs the array

    this.rows.push(test)    //Push the array to this.rows

    console.log(this.rows)  //Outputs array of objects
    consloe.log(this.rows[0])   //Outputs undefined
}

Event.ts

export interface TestEvent{
    id?: string,
    category?: string,
    event_name?: string
}

1 个答案:

答案 0 :(得分:3)

该代码没有问题,我测试了我的本地(typescript:2.5,angular5)。 我得到了 “row [0]:{id:”222“,类别:”testcat“,event_name:”name“}”

interface TestEvent{ 
id?: string,
  category?: string,
  event_name?: string
}

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

  rows: TestEvent[] = [];

  ngOnInit(){
    var test: TestEvent = {id: '222', category:'testcat', event_name: 'name'};
    console.log(test); // Outputs the array

    this.rows.push(test); //Push the array to this.rows

    console.log(this.rows); //=> 0:{id: "222", category: "testcat", event_name: "name"}
    console.log(this.rows[0]); // => {id: "222", category: "testcat",event_name: "name"}

    }
}