2017-01-16 96 views
1

訂閱前後完整能否請您回答評論等待HTTP請求執行下一行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()); 
} 
} 

質疑那麼我們如何能夠消除這種情況???或 有沒有什麼辦法讓SYNCHRONUS調用HTTP在角2

+0

您不希望它是同步的,因爲這會讓您的應用程序在等待響應時掛起。無論您需要對結果做什麼,您都必須在訂閱回調中執行操作。 –

回答

1

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

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

,因爲你的訂閱方法以異步方式工作。我建議你也看看promises