【问题标题】:Push to array of interface type推送到接口类型数组
【发布时间】:2018-03-08 13:37:55
【问题描述】:

我有一个名为行类型 TestEvent 的数组,并且想要推送到数组,我无法输出我推送的对象它只显示未定义 如您所见,this.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
}

Event.ts

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

【问题讨论】:

  • 首先编写格式化且可以转译的代码。然后查看标记的重复项,您不应该使用this,因为rows 似乎是一个局部变量。
  • 我忘了说推送是在方法内部运行的
  • 这肯定会影响this,具体取决于调用方法的方式。 this 可以与浏览器窗口对象相关联。

标签: angular typescript


【解决方案1】:

该代码没有问题,我在本地(打字稿: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"}

    }
}

【讨论】:

  • 谢谢!在使用 push 之前先将对象分配给变量。
猜你喜欢
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2022-11-24
  • 2020-02-21
  • 1970-01-01
相关资源
最近更新 更多