简体   繁体   English

可以观察到不能正常工作angular2吗?

[英]Observable not working properly angular2?

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!!');
    }

}

I am calling above method through my template 我正在通过模板调用上述方法

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

I have user data with two users, Ram and Sai . 我有两个用户RamSai用户数据。 I logged as Ram and Sending message to Sai. 我以Ram身份登录并向Sai发送消息。 In recipient box I mentioned Sai and typed some message in message box. 在收件人框中,我提到了Sai,并在消息框中键入了一些消息。 When I click on send message, first time the message not getting pushed into sai's inbox as doing in sendMsg() method because it is going to else statement and printing Try again!! 当我单击send message时,第一次将消息没有像sendMsg()方法那样被推入sai的收件箱中,因为这是要发送到else语句并打印的Try again!! . On second+ clicks its getting pushed. 在第二+点击它被推动。 In the same way, once push success, now If I mentioned no name in recipient box, for first time click it is taking the previous value that is Sai and pushing message, and second+ clicks it is taking null value and prints console message Try again!! 以同样的方式,一旦推送成功,现在如果我在收件人框中没有提到任何名称,则第一次单击该按钮将获取先前的值,即Sai并推送消息,而第二次单击则单击其获取空值并打印控制台消息, Try again!! . Please help me 请帮我

Since Observables are doing asynchronuous work, you have to put any followup code that needs data from the subscription into the callback: 由于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!!');
            }
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM