Reputation: 113
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
Upvotes: 0
Views: 7753
Reputation: 41
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);
Upvotes: 1
Reputation: 592
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 ();
.
Upvotes: 0
Reputation: 3387
You can use object de-structuring like this...
conversation=[];
obj = {
itemName:'paste',
itemPrice: '50$'
}
ngOnInit(){
this.conversation = [ { ...this.obj } ];
}
Upvotes: 0
Reputation: 38094
Maybe you want typed array:
public conversation: messageThread [] = [];
And to push values:
this.conversation.push(new dataModel.messageThread());
Upvotes: 1