如何在构造函数外访问构造函数的值
问题描述:
我正在使用angular2。在我的项目中,使用http.get()方法获取json内容并将其分配给一个变量。我想在构造函数之外访问这些变量值。我怎样才能使它成为可能?如何在构造函数外访问构造函数的值
在我用我的组件页面..
public result;
constructor(private http : Http){
this.http.get('http://192.168.0.100:8000/json1')
.map(response => response.json())
.subscribe(data =>{ this.result = data});
}
// I want to acces this.result outside the constructor and assigned to a public variable
public b = JSON.stringify(this.result);
// but it is not working
我如何可以访问此? 在此先感谢
答
从你的榜样,你为什么不能这样做呢?
public result;
public b;
constructor(private http : Http){
this.http.get('http://192.168.0.100:8000/json1')
.map(response => response.json())
.subscribe(data =>{
this.result = data;
this.b = JSON.stringify(this.result);
});
}
如果您需要设置它的值,然后用它做什么你可以调用一个方法为GET请求完成处理:
constructor(private http : Http){
this.http.get('http://192.168.0.100:8000/json1')
.map(response => response.json())
.subscribe(data =>{
this.result = data;
this.b = JSON.stringify(this.result);
},
err => console.log(err),
() => {
doStuffAndBisSet();
});
}
+0
thaks很多@chris它工作正常 –
答
您面临此问题,因为数据尚未准备好,订阅方法返回来自不同线程的数据,并且当您分配this.result =数据时,它为时已晚,即您.subscribe()完成之前使用this.result(并实际分配数据)。
我不确定这是否是最好的方法,但您可以做的是将.map方法赋值给变量,并且在构造函数之外调用变量的.subscribe方法。
所以,你可以这样做:
public result;
constructor(private http : Http)
{
this.http.get('http://192.168.0.100:8000/json1')
.map(response => response.json());
//.subscribe(data =>{ this.result = data}); comment this out
}
// I want to acces this.result outside the constructor and assigned to a public variable
public myMethod()
{
this.result.subscribe(data =>
{
console.log(data);
//do what you want here.
};
}
你不知道需要多长时间来执行这个和变量可用时,请将请求移至某个方法并在需要时调用该方法。 – Alex