angular2可观察到,在组件中变得未定义 [英] angular2 observable, getting undefined in component

查看:60
本文介绍了angular2可观察到,在组件中变得未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular2的新手,我需要一些帮助. 我正在使用以下服务类别.

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

推荐答案

角度2 HTTP请求返回与其他代码异步运行的Observable.在ngOnInit()中,您预订getUsers()返回的Observable,然后在预订之外,您拥有console.log().

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().

换句话说,console.log(this.users)getUsers()实际完成HTTP请求以实际获取用户之前以及订阅将其分配给this.users之前运行.

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.

更改ngOnInit()这样,您将看到所需的结果:

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

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

另请参阅:

关于Observable的RxJS文档

HTTP客户端上的Angular 2文档

这篇关于angular2可观察到,在组件中变得未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆