Waiting for an answer from server on http request in Angular 2

泪湿孤枕 提交于 2019-12-05 09:26:34

In the service, you should return the Observable that your component can subscribe to. It cannot work they way you do it due to the asynchronous mode of the get request.

As a proposal, your service could look similar to this

getUsers() {
    let headers = new Headers();
    headers.append('Accept', 'q=0.8;application/json;q=0.9');

    return this.http.get('/AngularApp/api/users', { headers: headers })
        .map((res: Response) => res.json());
}

And the relevant part of your component like this:

 constructor(private userService:UserService) {
    this.userService.getUsers().subscribe(
      data => this.iterateOverUsers(data));
 }

 iterateOverUsers(data) {
   // here comes your for loop
 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!