简体   繁体   English

在角度/打字稿中推送类数组中的类对象

[英]Push class objects in class array in angular/typescript

i have an Agent class我有一个代理类

export class Agent{
    ID:number;
    Name: string;
}

And in component i have a variable of this class array在组件中,我有一个此类数组的变量

public agents : Agent[];

Now how can i push values in this variable?现在我如何在这个变量中推送值? I have tried following methods but no one worked.我尝试了以下方法,但没有人奏效。

agents.push({"ID":1,"Name":"Abc"});
agents.push(new Agent(){"ID":1,"Name":"Abc"});
agents.push(<Agent>{ ID:1, Name:"Abc" });

or或者

const _agent = new Agent();
_agent.ID = 1;
_agent.Name = "ABC";

agents.push(_agent);

You need to initialize your array, otherwise you'll get a "cannot read property 'push' of undefined" error.您需要初始化您的数组,否则您将收到“无法读取未定义的属性 'push'”错误。 Using a plain object like you did is fine (it's good practice to remove the quotes around the props), eg像您一样使用普通对象很好(删除道具周围的引号是一种很好的做法),例如

let agents : Agent[] = [];
agents.push({ ID: 1, Name: "Abc"});
console.log(agents); // outputs: [ { ID: 1, Name: 'Abc' } ]

If you actually want to create an instance of the class, you can do it like this:如果你真的想创建一个类的实例,你可以这样做:

const agent = new Agent();
agent.ID = 1;
agent.Name = "ABC";
agents.push(agent);

I think, merely change:我想,只要改变:

public agents : Agent[]; to public agents : Agent[] = [] public agents : Agent[] = []

and (if you still in the same component and inside a method) :和(如果你仍然在同一个组件和方法中):

agents.push({"ID":1,"Name":"Abc"}); to this. this. agents.push({"ID":1,"Name":"Abc"});


Update:更新:

If you're within the same method:如果您使用相同的方法:

someMethod(){
  let localAgents :Agent[]= []; 
  localAgents.push({ID:1,Name:"Abc"});
}

If you want to push while declaring, that cannot be done, you merely initialize with default data, why would you push ?如果你想在声明时推送,那是做不到的,你只是用默认数据初始化,你为什么要push

Eg例如

  public agents : Agent[] = [{ID:1,Name:"Abc"}];

DEMO演示

First, your class needs a constructor in order to initialize it with params首先,您的类需要一个构造函数以便使用 params 对其进行初始化

export class Agent {
    ID: number;
    Name: string;

    constructor(id: number, name: string) {
        this.ID = id;
        this.Name = name;
    }
}

Then, in your component然后,在您的组件中

...
public agents : Agent[];
...
pushAgent(id: number, name: string) {
    this.agents = [new Agent(id, name)]
}
  • Keep in mind, if you want Angular to display the content of the agents, you must change the array by reference.请记住,如果您希望 Angular 显示代理的内容,则必须通过引用更改数组。 Otherwise angular would not detect the changes.否则 angular 将无法检测到变化。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM