简体   繁体   English

angular2可观察到,在组件中变得不确定

[英]angular2 observable, getting undefined in component

I am new on angular2, I need some help. 我是angular2的新手,我需要一些帮助。 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 谢谢

Angular 2 HTTP requests return Observables that are run asynchronously from other code. Angular 2 HTTP请求返回与其他代码异步运行的Observable。 In the ngOnInit() , you subscribe to the Observable that getUsers() returns, and then outside of the subscription, you have the console.log() . ngOnInit() ,您订阅getUsers()返回的Observable,然后在订阅之外,您拥有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 . 换句话说, console.log(this.users)getUsers()实际完成HTTP请求以实际获取用户之前以及订阅已将其分配给this.users之前this.users

Alter ngOnInit() like so and you will see the desired result: 像这样更改ngOnInit() ,您将看到所需的结果:

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

See also: 也可以看看:

RxJS docs on Observables 关于Observables的RxJS文档

Angular 2 docs on the HTTP client HTTP客户端上的Angular 2文档

观察对象准备就绪后,this.user将立即可用,在此之前,您必须使用* ngIf保护HTML代码,以避免出现异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM