【问题标题】:Wait for Http Request complete before executing next line after subscribe in angular2等待 Http 请求完成,然后在 angular2 中订阅后执行下一行
【发布时间】:2017-01-17 00:42:58
【问题描述】:

你能在评论中回答问题吗

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

那么我们如何才能消除这种情况???或者 有什么方法可以在角度 2 中对 http 进行同步调用

【问题讨论】:

  • 您不希望它是同步的,因为这会使您的应用程序在等待响应时挂起。无论您需要对结果做什么,都必须在订阅回调中执行。

标签: angularjs


【解决方案1】:

如果你需要在这种情况下进行同步调用,你的代码应该是这样的:

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

因为您的订阅方法是异步工作的。我建议你也看看promises

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 2019-02-11
    • 1970-01-01
    • 2017-12-21
    • 2021-04-13
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多