如何在构造函数之外访问数据

时间:2019-05-06 07:24:21

标签: angular typescript

这是我的 $(document).ready(function(){ $('#tables').change(function(){ var selected = $(this).val(); $.ajax({ url:'http://localhost/control_cuotas/getData/'+selected }); }); }); }

var app = gplay.app({ appId: "com.google.android.youtube" });
app.then((result)=>console.log(result.title))

如何在构造函数之外获取数据?

4 个答案:

答案 0 :(得分:0)

首先,由于JavaScript / TypeScript的异步属性,因此无法访问订阅块之外的organizations属性。您可以通过here阅读有关事件循环的更多信息,因为它提供了更详细的说明。因此,您将需要使用.subscribe()返回可观察的值。

问题

this.access.getOrganizations().subscribe((data => {
  this.organizations = data;
}));
console.log(this.organizations);

console.log(this.organizations);将在订阅完成之前完成执行,因此它将打印值undefined。打印organizations的正确方法是改为:

this.access.getOrganizations().subscribe((data => {
  this.organizations = data;
  console.log(this.organizations);
}));

此外,如注释中所述,您不应在构造函数上返回observable。我建议您改为在OnInit生命周期中将其退回。

ngOnInit(): void {
  this.access.getOrganizations().subscribe((data => {
    this.organizations = data;
    console.log(this.organizations);
  }));
}

或者,您可以将其存储为可观察的对象,然后在真正需要时将其返回。

organizations: Observable<any>;

ngOnInit() {
  this.organizations = this.access.getOrganizations();
}

someOthermethod() {
  this.organizations.subscribe(res => {
    console.log(res);
  });
}

答案 1 :(得分:0)

  

首先,您不应在构造函数中调用服务

     

Reserve the constructor for simple initialization such as wiring constructor parameters to properties. The constructor shouldn't do anything. It certainly shouldn't call a function that makes HTTP requests to a remote server as a real data service would.

您应将OrganisationsComponent修改为以下内容:〜

export class OrganisationsComponent {

  dataFromServer: Observable<any>;

  constructor(private access: OrganizationService) {}

  ngOnInit() {
    this.access.getOrganizations().subscribe((data => {
      this.organizations = data;
      console.log(this.organizations);
    }));
    // console.log(this.organizations); // undefined because by the time subscribe is called you are console logging it
    setTimeout(() => { console.log(this.organizations); },5000);
  } 
}
  

说明:〜

     

您不会在订阅块之外获取数据,因为它是   异步,您在那里没有价值!

     

     

精确未定义->'getOrganizations()'未返回Observable   在登录到控制台时。

     

因此,根据您的服务呼叫响应时间,您可以进行测试    setTimeout

一个简单的问题示例,STACKBLITZ

希望这会有所帮助!

答案 2 :(得分:0)

简单来说,您可以这样做

constructor(public access: OrganizationService) {}

get(){
    this.access.getOrganizations().subscribe((data => {
      this.organizations = data;
      console.log(this.organizations);
    }))
   console.log(this.organizations)
}

ngOninit(){
  this.get();
}

答案 3 :(得分:0)

您可以将可观察对象转换为承诺,然后等待它,以便在解决承诺时可以访问该值。

export class OrganizationsComponent {

    public organizations;

    constructor(public access: OrganizationService) {}

    async ngOnInit() {
        this.organizations = await this.access.getOrganizations()
          .pipe(first())
          .toPromise();
        console.log("Organization Name: ", this.organizations[0].name)
    }

}