【问题标题】:Waiting for an answer from server on http request in Angular 2在Angular 2中等待服务器对http请求的回答
【发布时间】:2016-07-11 21:11:35
【问题描述】:

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

这是我的代码:

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 循环,直到我从服务器获得答案,所以我只返回空数组。任何人都可以帮助我吗?

【问题讨论】:

    标签: http angular get


    【解决方案1】:

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

    作为建议,您的服务可能与此类似

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

    你的组件的相关部分是这样的:

     constructor(private userService:UserService) {
        this.userService.getUsers().subscribe(
          data => this.iterateOverUsers(data));
     }
    
     iterateOverUsers(data) {
       // here comes your for loop
     }
    

    【讨论】:

    • 非常感谢,现在一切正常 ;)
    猜你喜欢
    • 2018-11-13
    • 2018-06-14
    • 2018-03-16
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    相关资源
    最近更新 更多