-2

This is my component.ts

export class OrganizationsComponent {

  public organizations;

  constructor(public access: OrganizationService) {

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

How do I get data outside the constructor?

Sourav Dutta
  • 1,267
  • 1
  • 19
  • 25
Rajan rek
  • 322
  • 2
  • 8
  • Please add more description in your question. – Arash May 06 '19 at 07:31
  • 2
    [**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.**](https://angular.io/tutorial/toh-pt4) – Sourav Dutta May 06 '19 at 07:32
  • What are you getting in console? – Chris May 06 '19 at 08:09

4 Answers4

1

Simply, You can do like this

constructor(public access: OrganizationService) {}

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

ngOninit(){
  this.get();
}
Chris
  • 1,236
  • 2
  • 18
  • 34
0

First and foremost, you cannot access the organizations property outside of the subscribe block, because of JavaScript/TypeScript's asynchronous properties. You may read more about the Event Loop over here, as it provides a more detailed explanation. Therefore, you will need to use .subscribe() to return the observable value.

The problem with

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

is that console.log(this.organizations); will finish executing before the subscription is completed, hence it will print a value of undefined. The correct way of printing organizations is to do this instead:

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

In addition, as explained on the comments, you should not be returning the observable on the constructor. I recommend you to return it on the OnInit life cycle instead.

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

Alternatively, you may store it as an observable instead, and return it later when you really need it.

organizations: Observable<any>;

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

someOthermethod() {
  this.organizations.subscribe(res => {
    console.log(res);
  });
}
wentjun
  • 40,384
  • 10
  • 95
  • 107
0

First of all, you should not call the service inside the constructor

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.

You should modify your OrganisationsComponent to something like below:~

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);
  } 
}

Explanation:~

You will not get the data outside the subscribe block because it's async, you don't have value there!

or

precisely undefined -> 'getOrganizations()' hadn't returned Observable by the time it's logging to console.

So, based on your service call response time you can test in setTimeout.

A simple example with your problem here STACKBLITZ

Hope this helps !

Sourav Dutta
  • 1,267
  • 1
  • 19
  • 25
0

You can convert the observable into the promise and await it so when the promise will be resolved the value will be accessible.

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)
    }

}
Balaj Khan
  • 2,490
  • 2
  • 17
  • 30