I have an angular app where I am using a third party chat plugin ng-chat. To implement its chat adapter I have to override a method
getMessageHistory(userId: any): Observable<Message[]>
In this method I am calling my service method to get the data from my server
this.userService.getChatHistory
and subscribe to it , once the data is available I want to construct the array of messages and return from the overridden method getMessageHistory
But for some reason the statements in getMessageHistory after the subscribe call is getting executed before the subscribe's callback are called.
Below is my code
Service method
public getChatHistory(loggedInUserId,selectedUserId){
let data = {"requestingUserProfileId": loggedInUserId, "targetUserProfileId":selectedUserId};
return this.http.post(this.apiEndPoint + '/xxx/', data, this.jwt())
.map((response: Response) => response.json());
}
In my adapter implementation
getMessageHistory(userId: any): Observable<Message[]> {
let msgHistory: Array<Message> =[];
this.userService.getChatHistory(this._loggedInUserId,userId).subscribe(
messages => {
if(messages ==null || messages.length ==0){
this.messages = [];
}
else{
console.log("messages retrieved are "+messages);
this.messages = messages;
for (var msg of this.messages) {
let tempMsg :Message = new Message();
console.log("from id is ",msg.fromId);
tempMsg.fromId= msg.fromId;
tempMsg.toId= msg.toId;
tempMsg.message= msg.messageText;
msgHistory.push(tempMsg);
}
}});
console.log("msgHistory array ",msgHistory); //==> This is getting //executed before the messages => { in the subscribe above
return Observable.of(msgHistory);
}
In My output I can see
msgHistory array []
being printed before
messages retrieved are [object Object],[object Object]
So my msgHistory array being returned is always empty. Is there a way that empty msgHistory is not returned, i.e. code should wait for subscribe call to finish before proceeding with the return statement?
I have also tried putting the logic
this.userService.getChatHistory(this._loggedInUserId,userId).subscribe
in a separate function and returning it, even then same issue.