简体   繁体   English

在 angular2 中订阅后,在执行下一行之前等待 Http 请求完成

[英]Wait for Http Request complete before executing next line after subscribe in angular2

Can you please answer to question in comment你能在评论中回答问题吗

class TextComp 
{

result: string;
constructor() {

    this.getdata().subscribe(result => {
        console.log("result received");
        this.result = result;
    });

    console.log("called before result received " + this.result);

    //this.result is NULL/UNDEFINED because this line executed before data received

    // So how we can eliminate this situation??? or
    // Is there any way to make synchronus call to http in angular 2
}

getdata() {
    return http.get('test.json')
        .map(response => response.json());
}
}

So how we can eliminate this situation???那么我们如何才能消除这种情况??? or Is there any way to make synchronus call to http in angular 2或者有什么方法可以在angular 2中同步调用http

if you need to make synchronous calls in this case your code should be something like:如果你需要在这种情况下进行同步调用,你的代码应该是这样的:

this.getdata().subscribe(result => {
    console.log("result received");
    this.result = result;
    //function or snippet which will be called after subscribe is complete...     
});

because your subscribe method works asynchronously.因为您的 subscribe 方法是异步工作的。 I recommend you also to take a look at promises .我建议你也看看promises

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

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