簡體   English   中英

在 angular2 中訂閱后,在執行下一行之前等待 Http 請求完成

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

你能在評論中回答問題嗎

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

那么我們如何才能消除這種情況??? 或者有什么方法可以在angular 2中同步調用http

如果你需要在這種情況下進行同步調用,你的代碼應該是這樣的:

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

因為您的 subscribe 方法是異步工作的。 我建議你也看看promises

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM