0

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

2
  • What kind of an array are you expecting to get as a result? an array of MessageThreads? if so then just push to the conversation the new Object. Commented Dec 11, 2019 at 7:13
  • Why you assign object to the array. If you have only one object then array is of no use and if you have multiple objects then you have to push in Array. Any specific reason you are assigning object to array? Commented Dec 11, 2019 at 7:35

4 Answers 4

1

Maybe you want typed array:

public conversation: messageThread [] = [];

And to push values:

this.conversation.push(new dataModel.messageThread());
Sign up to request clarification or add additional context in comments.

Comments

1

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);
    

Comments

0

You can use object de-structuring like this...

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

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

Comments

0

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 ();.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.