目前我有一个小API,我正在从中学习angular2来检索一些用户数据。
我创建了一个用户类[user.ts
]:
export class User {
first_name: string;
last_name: string;
email: string;
}
然后服务[user.service.ts
]:
import {Http} from '@angular/http';
import {User} from '../models/user';
import 'rxjs/add/operator/toPromise';
export class UserService {
private usersUrl = 'http://localhost:8000/api/user';
constructor(private http: Http) {
}
getUsers(): Promise<User[]> {
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
我有一个家庭组件,我试图显示用于测试目的的用户列表(稍后将用户列表更改为组件)。
import {OnInit, Component} from '@angular/core';
import {UserService} from '../services/user.service'
import {User} from "../models/user";
@Component({
selector: '<home>',
templateUrl: 'app/templates/user.component.html',
})
export class HomeComponent implements OnInit {
users: User[];
constructor(private userService: UserService) {
}
getUsers() {
this.userService.getUsers().then(users => this.users = users);
}
ngOnInit() {
this.getUsers();
}
}
我在app.component.ts:
providers: [
UserService
]
最后我尝试显示数据:
<div *ngIf="users" class="ui celled animated list">
<div *ngFor="let user of users" class="item">
<div class="content">
<div class="header">{{ user.first_name }} {{ user.last_name }}</div>
{{ user.email }}
</div>
</div>
</div>
还有什么需要做的吗?
检索的JSON如下:
[
{
"id":1,
"first_name":"Jameson",
"last_name":"Ziemann",
"email":"hank.runte@example.net",
"created_at":"2016-07-07 06:24:25",
"updated_at":"2016-07-07 06:24:25"
}
]
答案 0 :(得分:3)
是的,首先您需要将HTTP_PROVIDERS
添加到providers数组:
providers: [
HTTP_PROVIDERS,
UserService
]
第二,你需要让你的服务可注入,所以Angular 2知道它实际上必须通过依赖注入来解析构造函数参数:
import {Http} from '@angular/http';
import {User} from '../models/user';
import 'rxjs/add/operator/toPromise';
@Injectable() // <-- annotation for Angular 2
export class UserService {
private usersUrl = 'http://localhost:8000/api/user';
constructor(private http: Http) {
}
同样在UserService
中,您尝试在反序列化后访问data
属性,您已经获得了数组。考虑删除它:
getUsers(): Promise<User[]> {
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}