ng对于不起作用,控制台中没有错误



user.service.ts

@Injectable()
export class UserService  {constructor(private http: Http) {
}
getUsers(): Observable<User[]> {
console.log("in users http Get request");
return this.http.get("/assets/users.json")
.map((res: Response) => res.json());

用户.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { UserService } from './user.service';
import { Observable } from 'rxjs/Rx';
@Component ({
selector: 'users',
providers: [UserService],
template :`<div>
<table>
<tr *ngIf="!users || users.length==0"> Unable to load data </tr>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr *ngFor="let user of users" style="border:1px solid red">
<td>{{user.id}}</td>
<td>{{users.name}}</td>
</tr>
</table>
<br/>
</div>`
})
export class User{   //created user class with properties
UserService: Observable<User[]>;
user: string;
constructor(public service1:UserService) {
} 
ngOnInit() {
console.log("in ngoninnit");
this.UserService = this.service1.getUsers();
}   
}

用户.json

[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan@yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
}
]

我得到以下结果:

Unable to load data
ID  Name

未获取用户数据。

除了拼写错误之外,您没有在任何地方调用订阅:

export class User{   //created user class with properties
UserService: Observable<User[]>;
ngOnInit() {
this.UserService = this.service1.getUsers();
}   
}

由于您要保存可观察量,因此必须使用异步来触发获取数据:

<tr *ngFor="let user of users | async"

相关内容

最新更新