Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70435

How to add an object to nested array in Ionic app?

$
0
0

@Sweg wrote:

In my Ionic 5 app, I am trying to push a Message object into an array located within a Conversation object.

Here are the models I’m using:

export class Conversation {
    constructor(
        public id: string,
        public userId: string,
        public mechanicId: string,
        public messages: Message[]
    ) { }
}

export class Message {
    constructor(
        public id: string,
        public text: string,
        public userId: string,
        public timestamp: Date
    ) { }
}

I am able to create a new Conversation with the below code:

addConversation(mechanicId: string, message: string) {
    const newConversation = new Conversation(
      Math.random().toString(),
      this.authService.userId,
      mechanicId,
      [this.createMessage(message)]
    );
    return this.conversations.pipe(
      take(1),
      delay(1000),
      tap(conversations => {
        this._conversations.next(conversations.concat(newConversation));
      }));
  }

  private createMessage(message: string): Message {
    return {
      id: Math.random().toString(),
      text: message,
      userId: this.authService.userId,
      timestamp: new Date(Date.now())
    };
  }

But I am trying to push a new Message object into an existing Conversation object below:

addToConversation(id: string, mechanicId: string, message: string) {
    const conversation = this.getConversation(id);
    if (conversation) {
      conversation.messages.push(
        this.createMessage(message)
      );
    }
  }

But I’m getting this console error:

Property ‘messages’ does not exist on type Observable<{ id: string, userId: string, mechanicId: string, messages: Message; }>

Can someone please tell me how I can add a new Message to an existing Conversation using this method?

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70435

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>