也許你需要的東西是這樣的:
export class UserService {
getUsers() {
return fetch('http://localhost:8000/api/users')
.then(function(response) {
console.log(response);
return response.json();
});
}
}
在您的組件:
export class UserComponent implements OnInit {
users: any;
constructor(private userService: UserService) {}
ngOnInit() {
this.users = this.userService.getUsers();
}
}
並採用與async
管模板:
<div *ngFor="let user of users | async">
<span>Maybe print username: {{user.name}}</span>
</div>
如果你不這樣做想用async
管道:
在組件的代碼:
export class UserComponent implements OnInit {
users: any;
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUsers().then(data => {
// do something with response data
console.log(data);
this.users = this.someMethodToTransformResponse(data);
});
}
someMethodToTransformResponse(data) {
// return modification your data
}
}
和您的模板:
<div *ngFor="let user of users">
<span>Maybe print username: {{user.name}}</span>
</div>
你錯過了'return'。它應該是'return response.json()' – Phil
另外,你正在爲用戶分配一個承諾。你可能不想這樣試試'this.userService.getUsers()。then(users => this.users = users)' – Phil
@Phil也許他/她想要在模板中使用'async'管道:) –