I am new on angular2, I need some help. I am using below service class.
import {Injectable} from \'angular2/core\';
import {Http} from \'angular2/http\';
imp
this.user will be available as soon as the observable will be ready, until then, you have to protect your HTML code with *ngIf to avoid exceptions.
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