Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

angular

get

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?

like image 362
Celdur Avatar asked Jul 11 '16 21:07

Celdur


People also ask

How can I wait until my HTTP request finishes in angular?

Use . toPromise on your observable followed by async/await .

Which type of response is returned by HTTP service in angular?

HttpClient methods return one valuelink All HttpClient methods return an RxJS Observable of something. HTTP is a request/response protocol. You make a request, it returns a single response.

Which object does the HTTP get() function return?

response : interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.


1 Answers

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
 }
like image 173
Jan B. Avatar answered Oct 14 '22 16:10

Jan B.