2016-09-09 96 views
0
sendMsg(msgToSend: string, reciepient: string){ 
    console.log(msgToSend, reciepient, this.user); 
    let newObj = {from: this.user['name'], msg: msgToSend}; 
    this.sub = this.route.params.subscribe(params => { 
     let name = reciepient; 
     this.service.getUser(name).then(user => this.reciepient = user); 
    }) 
    if(this.reciepient){ 
     console.log(this.reciepient['inbox']); 
     this.reciepient['inbox'].unshift(newObj); 
    } else { 
     console.log('Try again!!'); 
    } 

} 

我打電話上述方法,通過我的模板Observable無法正常工作angular2?

<input #reciepient placeholder="Reciepient"/> 
<input #message placeholder="Enter your message"/> 
<button (click)="sendMsg(message.value, reciepient.value)">Send message</button> 

我有兩個用戶,RamSai用戶數據。我登錄爲Ram併發送消息給Sai。在收件人框中,我提到了Sai並在消息框中鍵入了一些消息。當我點擊發送消息時,第一次沒有將消息推入到sai的收件箱中,因爲它正在執行sendMsg()方法,因爲它正在去其他語句並打印Try again!!。第二次點擊推送。同樣,一旦推送成功,現在如果我在收件箱中沒有提到名稱,第一次點擊它是以先前的值爲Sai並推送消息,並且第二次點擊它爲空值並打印控制檯消息Try again!!。請幫我

回答

0

由於Observables正在做asynchronuous工作,你必須把任何後續的代碼,從預訂數據需要步入回調:

sendMsg(msgToSend: string, reciepient: string){ 
    console.log(msgToSend, reciepient, this.user); 

    let newObj = {from: this.user['name'], msg: msgToSend}; 

    this.sub = this.route.params.subscribe(params => { 
     let name = reciepient; 

     this.service.getUser(name).then(user => { 
      this.reciepient = user; 

      if(this.reciepient){ 
       console.log(this.reciepient['inbox']); 
       this.reciepient['inbox'].unshift(newObj); 
      } else { 
       console.log('Try again!!'); 
      } 
     }); 
    }); 
} 
+0

仍得到相同的輸出 –

+0

你能嘗試和調試呢?您可以在使用瀏覽器進行調試時設置斷點並逐步執行每條指令。只需按'F12'開啓開發者工具,切換到'Sources'選項卡並選擇js文件。 – rinukkusu