在Angular 2的http请求中等待来自服务器的答案 [英] Waiting for an answer from server on http request in Angular 2

查看:129
本文介绍了在Angular 2的http请求中等待来自服务器的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Angular2应用程序存在一个小问题。我想从我的用户登录服务器获取一些数据,但是我的代码正在继续,并且我有很多错误。我想等待服务器的回答,然后对我的数据做一些事情。

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;
    }

正如我注意到我的代码将进入for循环,直到我从服务器,所以我只返回空数组。任何人都可以帮助我吗?

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?

推荐答案

在服务中,您应该返回 Observable 你的组件可以订阅。由于 get 请求的异步模式,它无法按照它们的方式工作。

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
 }

这篇关于在Angular 2的http请求中等待来自服务器的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆