1

How to access this variable that is out of escope?

export class ClientsComponent implements OnInit { title: string = "All Clients"

clients: Client[] = [];
response: any;
total_clients: number;
total_pages: number;
pages: any[] = [];

constructor( private _clientService: ClientService ) {}

ngOnInit() {

   this._clientService.getData()
        .subscribe(
        data => this.response = data,
        err => console.error(err),
        () => {
            this.clients = this.response.data, 
            this.total_clients = this.response.total
            }
        );


    console.log(this.total_clients); <- i can not access this


}
user3050037
  • 111
  • 1
  • The console log occurs before the data is returned, you can use a callback function inside your subscribe to trigger logic and what not. – DylanH Oct 28 '16 at 18:17
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Oct 28 '16 at 18:19
  • Ok. However, i need handle this variable into foreach, but i can not do this into () => {}. How to ensure that this variable is used after loading? – user3050037 Oct 28 '16 at 18:22

2 Answers2

1

It isn't out of scope, it's simply not populated yet when this.total_clients in printed in console. All HTTP requests are asynchronous operations, so if you want to access it, you can to do it in subscription, like this:

ngOnInit() {

   this._clientService.getData()
        .subscribe(
        data => this.response = data,
        err => console.error(err),
        () => {
            this.clients = this.response.data, 
            this.total_clients = this.response.total
            console.log(this.total_clients); <- this will print your data
            }
        );


    console.log(this.total_clients); <- this is executed before the call is finished, as you will see


}
Stefan Svrkota
  • 48,787
  • 9
  • 98
  • 87
  • Ok. However, i need handle this variable into foreach, but i can not do this into () => {}. How to ensure that this variable is used after loading? – user3050037 Oct 28 '16 at 18:21
0

You need to initialize your variable in the constructor, then populate it in the callback from the async call. Here is the full code:

export class ClientsComponent implements OnInit { title: string = "All Clients"
  clients: Client[] = [];
  response: any;
  total_clients: number;
  total_pages: number;
  pages: any[] = [];

  constructor( private _clientService: ClientService ) {
    this.clients = [];
    this.total_clients = 0l
  }

  ngOnInit() {
    this._clientService.getData()
        .subscribe(
        data => {
          this.clients = this.response.data;
          this.total_clients = this.response.total;
        }
        err => console.error(err)
    );
  }
}
Ben Richards
  • 3,437
  • 1
  • 14
  • 18