我在开发一个类似聊天的应用程序时遇到了问题。我有一个包含所有相关消息的对话组件。这些消息有一个内部状态,在其模板中显示不同的图标。我在app.组件中注册了3个可观察对象,它们是这些
app组件
vm.socketService.newReadStatus$.subscribe(read_status => {
console.log('NEW SOCKET READ STATUS', read_status);
});
vm.socketService.newSocketConversation$.subscribe(conversation => {
console.log('NEW SOCKET CONVERSATION', conversation);
});
vm.socketService.newSocketMessage$.subscribe(socket_msg => {
const monitor = vm.infoService.getStructure(socket_msg.sid),
conversation = monitor.getConversation(socket_msg.cid),
message = conversation.getMessage(socket_msg.mid);
message.setConfirmed();
});
这是消息类结构(我将只发布相关部分)
消息. ts
constructor(message_data) {
_.extend(this, {
_account_id: message_data.aid,
_conversation_id: message_data.cid,
_message_id: message_data.mid,
_structure_id: message_data.sid,
_data: message_data.data,
_extra: message_data.extra,
_recipient: message_data.recipient,
_render: message_data.render,
_sender: message_data.sender,
_seq: message_data.seq,
_status: message_data.status,
_time: message_data.time ? message_data.time : moment(),
_temp_id: message_data._temp_id
});
if (message_data.sending_status) {
this._sending_status = message_data.sending_status;
} else {
this.setConfirmed();
}
}
setConfirmed() {
this._sending_status = {
pending: false,
confirmed: true,
error: false
};
}
用他的组件
export class MessageComponent {
@Input() message: Message;
constructor() {
}
getIcon() {
const vm = this, msg_status = vm.message.current_status;
let icon = '';
switch (msg_status) {
case 'pending':
icon = 'access_time';
break;
case 'confirmed':
icon = 'done';
break;
case 'error':
icon = 'error_outline';
break;
}
return icon;
}
}
而这是chat-会话.组件
里面的部分(只是消息发送的相关部分)
sendMessage() {
const vm = this;
if (vm.messageForm.valid) {
const last_seq = vm.conversation.getLastSeq(),
_temp_id = last_seq ? last_seq + 1 : 0,
msg_data = {
aid: vm.conversation.account_id,
mid: _temp_id,
sid: vm.monitor.structure_id,
cid: vm.conversation.conversation_id,
_temp_id: _temp_id,
data: {
text: vm.messageForm.get('message').value
},
seq: last_seq,
recipient: {
name: vm.conversation.name,
type: vm.conversation.type
},
render: 'staff',
sender: {
name: vm.infoService.getCurrentUser().name,
userId: vm.infoService.getCurrentUserID(),
type: 'staff'
},
status: {
timestamps: {
staffRead: new Date().valueOf()
}
},
sending_status: {
pending: true
},
time: null,
type: 'text'
};
vm.conversation.addMessage(msg_data).then(() => {
const temp_message = vm.conversation.getTempMessage(_temp_id);
if (temp_message) {
vm.apiService.post('chat/message', {
conversation: vm.conversation.conversation_id,
text: vm.messageForm.get('message').value,
recipient: 'staff',
sender: 'staff',
_temp_id: _temp_id
}).subscribe(
response => {
temp_message.message_id = response.mid;
}, error => {
temp_message.setError();
console.log('NEW MESSAGE ERROR', error);
}
);
}
});
}
}
它应该像这样工作
问题是视图只更新一次
经过非常长的调试过程,我发现我总是在搜索相同的message.id
只在第一次更新它。我真可耻