2017-01-16 104 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