Angular 如何让一个方法等待Observablesubscribe首先被调用,然后再继续处理其余的代码?

Angular 如何让一个方法等待Observablesubscribe首先被调用,然后再继续处理其余的代码?,angular,observable,Angular,Observable,我有一个angular应用程序,我正在使用第三方聊天插件ng chat。 要实现它的聊天适配器,我必须重写一个方法 getMessageHistory(userId: any): Observable<Message[]> 然后订阅它,一旦数据可用,我想构建消息数组并从重写的方法getMessageHistory返回 但是由于某些原因,在订阅调用之后的getMessageHistory中的语句是在调用订阅的回调之前执行的。 下面是我的代码 服务方式 public getChat

我有一个angular应用程序,我正在使用第三方聊天插件ng chat。 要实现它的聊天适配器,我必须重写一个方法

getMessageHistory(userId: any): Observable<Message[]>
然后订阅它,一旦数据可用,我想构建消息数组并从重写的方法getMessageHistory返回 但是由于某些原因,在订阅调用之后的getMessageHistory中的语句是在调用订阅的回调之前执行的。 下面是我的代码

服务方式

  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());


    }
在我的适配器实现中

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);


    }
因此,返回的msgHistory数组始终为空。 是否有一种方法不返回空的msgHistory,即代码在继续执行return语句之前应等待subscribe调用完成

我也试着把逻辑

this.userService.getChatHistory(this._loggedInUserId,userId).subscribe

在一个单独的函数中,并返回它,即使是相同的问题。

您需要了解订阅是一个异步操作;这意味着您订阅的可观察对象应该异步发出值。我能想到的唯一解决方案是将可观察序列转换为承诺,并将console.log语句放入.then函数中。您可以使用toPromise功能完成此操作。有关更多详细信息,请查看。

不确定,但您能否使用rxjs的first和flatMap运算符尝试以下代码:


为什么地图+平面地图的可观察。的。。。?您可以让map拥有msgHistory并返回它,这样您就不需要这样做了flatmap@olivarra1-事实上,这是正确的。我们还可以返回可观察的。。一旦响应被处理,就从map开始。更正。这仍然需要@TruckDriver使用实际的API进行测试。这里有一点设计问题。。。这是什么消息?在哪里使用?这与getMessageHistory有何不同@hemu的回答是有道理的,但是它的代码气味让人很难理解流,但是我不知道如何在没有更多关于用例的上下文的情况下改进它。
messages retrieved are [object Object],[object Object]
this.userService.getChatHistory(this._loggedInUserId,userId).subscribe
getMessageHistory(userId: any): Observable<Message[]> {
 let msgHistory: Array<Message> =[];
 return this.userService.getChatHistory(this._loggedInUserId,userId)
            .first()
            .map(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);

                    }

                }
                return Observable.of(msgHistory);
            });

}