angular2 observable, getting undefined in component

Angular 2 HTTP requests return Observables that are run asynchronously from other code. In the ngOnInit(), you subscribe to the Observable that getUsers() returns, and then outside of the subscription, you have the console.log().

In other words, the console.log(this.users) is running before the getUsers() has actually completed the HTTP request to actually get the users and before the subscription has assigned them to this.users.

Alter ngOnInit() like so and you will see the desired result:

ngOnInit(){
    this._service.getUsers()
        .subscribe(result => {
            this.users = result;
            console.log(this.users);
        });
} 

See also:

RxJS docs on Observables

Angular 2 docs on the HTTP client

Leave a Comment