推送到接口类型的数组 [英] Push to array of interface type

查看:70
本文介绍了推送到接口类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为TestEvent类型的行的数组,并且想要推送到该数组,我无法输出该对象,但我推送它只显示未定义的对象如您所见,this.rows显示了数组,但是当我尝试输出特殊数组this.rows [0]时,我不确定.(Typescript 2.7,Angular 5)

I have an array called rows of type TestEvent, and want to push to the array, i cant get to output the object i pushes it only shows undefined As you can see this.rows shows the arrays, but when i try to output a spesific array this.rows[0] i get undefined. (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
}

推荐答案

该代码没有问题,我在我的local(typescript:2.5,angular5)上进行了测试.我得到了"row [0]:{id:" 222,类别:" testcat,event_name:"名称}"

That code has no problem and I tested on my local(typescript : 2.5 , angular5). And I got "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"}

    }
}

这篇关于推送到接口类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆