我有一个聊天设计,其中的左侧有一个人列表,单击任何人,我都会在右侧打开他的聊天记录。因此,我需要使用RXJS订阅调用将用户详细信息从一个组件发送到另一个组件。现在,数据正在成功传输,但是问题是,在通过subscribe
正确的组件中的调用接收到用户详细信息之后,我正在调用一个API来使用户聊天记录,并希望在该组件中显示聊天记录,因此,我需要添加for循环API的成功响应,但for
循环未执行。下面是我的右侧组件代码。
` ngOnInit() {
this.userProfileId = this.utilService.getCurrentLoginUserProfileId();
if (this.userProfileId) {
this.friendId = this.userDetail.userProfileId;
// get users data
this.utilService.onChangeUserDetailData.subscribe(data => {
console.log('data', data);
if (data) {
this.userDetail = data;
this.friendId = this.userDetail.userProfileId;
this.sendUserOnlineSocket(data);
// get chat history api
this.getUsersChatData(data);
}
});
}
// get users chat data
getUsersChatData(user: any) {
let postObj;
if (user.chatRoomId) {
postObj = {
from_user: this.userProfileId,
to_user: user.chatRoomId
};
} else if (user.userProfileId) {
postObj = {
from_user: this.userProfileId,
to_user: user.userProfileId
};
}
this.chatPageService.getChatData(postObj).then((res: any) => {
console.log(' chat data res', res);
if (res['status'] === 200) {
if (res['data']['length'] > 0) {
for (let i = 0; i < res.data.length; i++) {
console.log('message response', res[i]);
if (res[i]['user_profile_id'] === this.userProfileId && res[i]['to_user_id'] === this.friendId) {
this.messageData.push({ side: 'right side', data: res[i] });
} else {
this.messageData.push({ side: 'left side', data: res[i] });
}
}
console.log('message data', this.messageData);
}
console.log('message data', this.messageData);
}
console.log('message data', this.messageData);
}).catch(err => {
if (err.hasOwnProperty('error')) {
this.utilService.errorHandler(err.error);
} else {
this.utilService.showError(
'Error',
this.utilService.commonErrorMsg
);
}
});
}
`
我已成功获取“聊天数据资源”控制台,但在for
循环中,我未定义“消息响应”,并且未执行以下控制台。请为我提出解决方案或其他选择。
根据您的代码,您正在犯一个错误。
而不是res[i]
你需要检查res.data[i]
for (let i = 0; i < res.data.length; i++) {
console.log('message response', res.data[i]);
}
选中上面的复选框,您将获取数据,更改之后,请替换res[i]['user_profile_id']
为res.data[i]['user_profile_id']
。随时随地对您的代码进行更改
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句