简体   繁体   中英

How to assign object to an empty array

In my angular6 application,

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.

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

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;

 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. If you want to assing the object to conversation variable. Why don't you put the type of conversation or assign it like an empty object. conversation = {} and then make it Equals to this this.conversation = new dataModel.messageThread (); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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