简体   繁体   English

如何将对象分配给空数组

[英]How to assign object to an empty array

In my angular6 application,在我的 angular6 应用程序中,

I have declared empty array as below:我已声明空数组如下:

conversation=[]

and I have constructor in shared module where it does initialize the object of conversation below is the code我在共享模块中有构造函数,它确实初始化了下面的对话对象是代码

export class messageThread {
    internalId?: number;
    unreadMessageCount?: number;
    subject?: string;
    managerCode?: string;
    constructor(json?: any) {
        if ( !json ) return;
        this.internalId= json.internalId || 0;
        this.unreadMessageCount=json.internalId || 0;;
        this.subject = json.internalId || '';
        this.managerCode =json.managerCode|| '';

    }
}

However when in my ts file if I do like below.但是,如果我喜欢下面的内容,则在我的 ts 文件中。

this.conversation = new dataModel.messageThread (); 

it gives me error: saying that only push, pop can be used, I know that this is because I have initialized it with empty array and it does expect array as an assignment, is there any way we can assign object to an empty array or I am missing something here它给了我错误:说只能使用 push、pop,我知道这是因为我已经用空数组初始化它并且它确实希望数组作为赋值,有什么方法可以将对象分配给空数组或我在这里遗漏了一些东西

Maybe you want typed array:也许你想要类型化数组:

public conversation: messageThread [] = [];

And to push values:并推动价值:

this.conversation.push(new dataModel.messageThread());

while working on angular alway keep in mind that angular is javascript framework so you can use any javascript function in angular as per you question you can simplly use .push() function on your array;在处理 angular 时,请始终记住 angular 是 javascript 框架,因此您可以根据您的问题在 angular 中使用任何 javascript 函数,您可以简单地在数组上使用 .push() 函数;

 var abc = []; obj = {itemName:'paste',itemPrice: '50$'}; abc.push(obj); console.log(abc);

You can use object de-structuring like this...您可以像这样使用对象解构...

conversation=[];
obj = {
  itemName:'paste',
  itemPrice: '50$'
}

ngOnInit(){
   this.conversation = [ { ...this.obj } ];
}

It doesn't make sense to assign an object to an Array type.将对象分配给 Array 类型是没有意义的。 If you want to assing the object to conversation variable.如果要将对象分配给conversation变量。 Why don't you put the type of conversation or assign it like an empty object.你为什么不把conversation的类型或者像一个空对象一样分配它。 conversation = {} and then make it Equals to this this.conversation = new dataModel.messageThread (); conversation = {}然后让它等于this.conversation = new dataModel.messageThread (); . .

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

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