创建Angular对象时,如何将值传递给内部数组



以下是Conversation&我在Ionic 5/Angular应用程序中使用的Message型号:

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: string
) { }
}

当用户创建Conversation对象时,我希望他们在Conversation中添加1个Message对象。

然后,当其他用途是更新Conversation(即发送更多消息(时,它们将只是将另一个Message推送到Conversation

以下是我迄今为止创建Conversation:的内容

onSendMessage() {
this.conversationService.addConversation(
this.mechanicToContact.id,
this.form.value.message
);
}

我在ConversationService中尝试了以下方法:

addConversation(mechanicId: string, message: string) {
const newConversation = new Conversation(
Math.random().toString(),
this.authService.userId,
mechanicId,
new Message(Math.random().toString(), message, this.authService.userId, mechanicId)
);
}

但我在尝试创建新消息时遇到了这个错误:

"Message"类型的参数不可分配给"Message[]"的类型参数

我不确定应该如何传递Message的其余属性。有人能告诉我这是怎么做的吗?

好吧,类Conversation需要一个Message[],这是一个消息数组,而您正在发送Message。有几种方法可以解决这个问题。一个是:

const newConversation = new Conversation(conversationId, userId, mechanicId, [ message ]);

这只是将消息封装在一个数组中。


另一个:

export class Conversation {
public messages: Message[];
constructor(
public id: string,
public userId: string,
public mechanicId: string,
messages: Message | Message[]
) { 
this.messages = Array.isArray(messages) ? messages : [ messages ];
}
addMessages(messages: Message | Message[]): void {
this.messages.push(
...(Array.isArray(messages) ? messages : [ messages ])
);
}
}

这将能够接受数组作为消息对象,并在类内以正确的方式进行处理。


让服务处理这个问题更为常见。你可以这样想:

export interface Conversation {
id: string;
userId: string;
mechanicId: string;
messages: Message[];
}
@Injectable({
providedIn: 'root'
})
export class ConversationService {
private conversations: Conversation[];
addConversation(mechanicId: string, message: string): Conversation {
const conversation: Conversation = {
id: getUniqueUid() // something like this,
userId: this.userService.getUserId() // something like this
mechanicId,
messages: [ this.createMessage(message) ] 
};
this.conversations.push(conversation);
return conversation;
}
addToConversation(id: string, mechanicId: string, message: string): Conversation {
const conversation = this.getConversation(id);
if (conversation) {
conversation.messages.push(
this.createMessage(message)
);
}
return conversation;
}
private createMessage(message: string): Message {
return {
id: getUniqueMid() // something like this,
text: message,
userId: this.userService.getUserId(),
timestamp: Date.now()
};
}
private getConversation(id: string): Conversation | undefined {
return this.conversations.find((conversation) => conversation.id === id); 
}
}

您的addConversation函数应该是这个

addConversation(userId: string, mechanicId: string, messages: Message[]) {
const newConversation = new Conversation(conversationId, userId, mechanicId, messages);
}

您在会话类中使用了一个数组,但只给它一条消息作为参数。

最新更新