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!!');
}
}
我通过我的模板调用上面的方法
<input #reciepient placeholder="Reciepient"/>
<input #message placeholder="Enter your message"/>
<button (click)="sendMsg(message.value, reciepient.value)">Send message</button>
我拥有两位用户Ram
和Sai
的用户数据。我记录为Ram并向Sai发送消息。在收件人框中,我提到了Sai并在消息框中输入了一些消息。当我点击发送消息时,第一次消息没有像在sendMsg()方法中那样被推入sai的收件箱,因为它将转到else语句并打印Try again!!
。在第二个+点击它被推动。以同样的方式,一旦推动成功,现在如果我在收件人框中没有提到名字,第一次点击它是先前的值是Sai和推送消息,第二次+点击它取空值并打印控制台消息{{ 1}}。请帮帮我
答案 0 :(得分:0)
由于Observables
正在进行异步工作,您必须将需要订阅数据的任何后续代码放入回调中:
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!!');
}
});
});
}