-1

I have an Angular 7.x app - I have component that calls a function within a service - this does an GET request to a backend endpoint and returns an array of users;

I am able to see the data within the subscribe (where I have used the console.log) - however I am not able to use the data outside out subscribe() - how do I get access to the data from this.userAccessList

// top of component
public userAccessList: Array<any> = [];

checkAccess(): void {
    this.chatMessagesService.getListWithAccessToPage()
      .subscribe(json => {
        console.log(json); // can see this in the console in the browser
        this.userAccessList = json;
      });

    console.log('userAccessList', this.userAccessList); // appears as  an  empty array
}
Zabs
  • 13,852
  • 45
  • 173
  • 297
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe May 14 '20 at 12:06

1 Answers1

1

We're dealing with asynchronous requests here.So, the console.log('userAccessList', this.userAccessList); may be executed before the api call completes. So, it might not be available at that point.

If you want to use this value in template, check if the value exists first as below.

<span *ngIf="userAccessList"> <!-- Do stuff --> </span>
Akhil Chandran
  • 380
  • 3
  • 12