如何在构造函数外部访问构造函数值



我正在使用 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();
     }); 
  }

您面临此问题是因为数据尚未准备就绪,订阅方法从不同的线程返回数据,当您分配this.result = data时,为时已晚,即您在.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.
    };
 }  

最新更新