Angular2 Http 获取

Angular2 Http get

我正在尝试使用 Angular2 从 API 中提取数据,并将其绑定到视图。请求完成后,我的组件只得到数组对象 [object Object],[object Object],[object Object]。我能否在提取对象方面获得任何帮助,以便 "*ngFor" 可以读取每个对象。我希望能够绑定数据查看。

**This is my API**
[{
    _id: "578c8c670f3cd0941efb337c",
    name: "John",
    gender: "Male",
    age: "34",
    __v: 0,
},
{
    _id: "5794a90f96391dcc2436e43f",
    name: "Valur",
    gender: "Male",
    age: "22",
    __v: 0,
},
{
    _id: "5794abad70df28541eab170b",
    name: "Paul",
    gender: "Male",
    age: "43",
    __v: 0,
}]

用户服务就像:

import { Http } from 'angular2/http';
constructor(private _http: Http) { }

getuser(): Observable<any> {
     return this._http.get('http://localhost:1000/api/users')
     .map(res => res.json());
}

这是我的 angular 处理请求的服务。

import { UserService } from '../services/userservice';

constructor(private userService: UserService) { }
_data: Object;

getUser():void {
    this.userService.getuser()
      .subscribe(data => this._data = data,
      error => console.log(error));

    console.log(this._data); //this part doesn't pull data at all.
}


//My view
<div *ngFor="#u of _data">
   {{u.name}} //this part gives me an error
</div>

 //But when i try to pull data from "subscribe" like this:
<div>
   {{_data | json }} //data is available
</div>

试试这个。

import { UserService } from '../services/userservice';

_data: any[];
constructor(private userService: UserService) { this._data = [];}

getUser():void {
  this.userService.getuser()
    .subscribe(data => {this._data = data; console.log(this._data);}
                error => console.log(error));
 }


 //My view
 <div *ngFor="#u of _data">
   {{u?.name}} //this part gives me an error
 </div>

我同意 Günter 的观点,错误正是在 *ngFor 的语法中,我已经测试了你的代码,并做了一个工作示例:

https://github.com/TheSwash/ng2-http-service

但很快正确的语法应该是:

<div *ngFor="let user of users">
   {{user.name}}
</div>

此外,我强烈建议您更新 angular 版本,您使用的是测试版。目前您可以使用 Angular-CLI:https://cli.angular.io/

上面的例子是用Angular-CLI制作的。