angular2 observable, getting undefined in componen

2020-01-27 08:39发布

问题:

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';
import 'rxjs/add/operator/map';

@Injectable()
 export class UsersService {
    private _url = "http://jsonplaceholder.typicode.com/users";

    constructor(private _http: Http){
    }

    getUsers(){
        return this._http.get(this._url)
            .map(res => res.json());
    }
 }

when I am calling above service in below component, I get undefined value.

import{Component, OnInit} from 'angular2/core';
import{UsersService} from './users.service';

@Component({
    selector: 'users',
    template:'In users',
    //templateUrl: 'app/users.component.html',
    providers: [UsersService] 
})

export class UsersComponent implements OnInit{
users: any[];

    constructor(private _service: UsersService){
    }

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

        console.log(this.users);
    } 
}

But if I tried to log the value in the console in service class, its shows there. any help would be highly appreciable. Thanks

回答1:

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



回答2:

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