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

China☆狼群 提交于 2019-12-07 05:21:31

问题


I have a little problem with my Angular2 app. I want to get some data from server for my user login, but my code is going ahead and I have a lot of bugs with it. I want to wait for answer from server, then do something with my data.

This is my code:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { User } from './user';

@Injectable()

export class UserService {

    public usersTmp: Array<Object> = new Array<Object>();
    public users: Array<User>;
    public user: User = new User();
    public noteToSend;
    constructor(private http: Http) { }

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

        this.http.get('/AngularApp/api/users', { headers: headers })
            .map((res: Response) => res.json())
            .subscribe(
            data => {
                console.log(data);
                this.usersTmp = data;
            },
            err => console.error(err),
            () => console.log('done')
            );

        this.users = new Array<User>();
        for (var i = 0; i < this.usersTmp.length; i++) {
            this.user = new User();
            this.user.id = this.usersTmp[i]["userId"];
            this.user.name = this.usersTmp[i]["userName"];
            this.user.email = this.usersTmp[i]["userEmail"];
            this.user.pass = this.usersTmp[i]["userPassword"];

            this.users.push(this.user);

        }
        return this.users;
    }

As I noticed my code is going to the for loop until I get answer from server, so I return just empty array. Anyone can help me with that?


回答1:


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
 }


来源:https://stackoverflow.com/questions/38316300/waiting-for-an-answer-from-server-on-http-request-in-angular-2

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