angular2可观察到,在组件中变得未定义

编程入门 行业动态 更新时间:2024-10-26 16:28:43
本文介绍了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 = "jsonplaceholder.typicode/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/usersponent.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可观察到,在组件中变得未定义

本文发布于:2023-11-22 23:17:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619304.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   未定义   观察到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!