推送到接口类型数组

Vla*_*d J 5 typescript angular

我有一个名为TestEvent类型的行的数组,并且想要推送到该数组,我无法输出对象,我推送的对象仅显示未定义,如您所见,rows显示了数组,但是当我尝试输出特殊的数组时数组this.rows [0]我不确定。(打字稿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
}
Run Code Online (Sandbox Code Playgroud)

Event.ts

export interface TestEvent{
    id?: string,
    category?: string,
    event_name?: string
}
Run Code Online (Sandbox Code Playgroud)

Jih*_*won 7

该代码没有问题,我在本地(打字稿:2.5,angular5)上进行了测试。我得到了 "row[0] : {id: "222", category: "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"}

    }
}
Run Code Online (Sandbox Code Playgroud)