In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Data transfer is successful, but I encounter an issue after receiving user details through the subscribe
call in the right component. I make an API call to fetch users' chat history and display chats in that component. However, when I try to run a for
loop in the success response of the API, it does not execute. Below is the code of my right side component:
` 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
);
}
});
}
`
I can see 'chat data res' in the console, however, the 'message response' inside the for
loop returns undefined and the subsequent consoles are not executed. Can someone provide a solution or suggest an alternative approach for this issue?