angular2 observable, getting undefined in component

前端 未结 2 375
悲&欢浪女
悲&欢浪女 2020-11-30 15:49

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         


        
相关标签:
2条回答
  • 2020-11-30 16:21

    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.

    0 讨论(0)
  • 2020-11-30 16:46

    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

    0 讨论(0)
提交回复
热议问题