Angular 2服务 - 如何返回一个对象数组?

时间:2018-01-10 21:45:52

标签: javascript arrays typescript angular2-services

我有Angular 2服务组件,用于填充对象数组。我想从程序中的其他组件中获取该数组。但是,在下面显示的代码中,getUsers()始终返回null。

如何让getUsers()返回populateUsers()中填充的数组?

服务组件代码:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { ContainerUser } from '../models/container-user';
import { ContainerService } from './container.service';
import { OnInit } from '@angular/core';

@Injectable()
export class UserService {
private _containerUsers: ContainerUser[];
private _currentUserId: string;
private _currentUserName: string;
errorMessage: string;

constructor(private _containerService: ContainerService, private _router: Router) { this.populateUsers(); };

populateUsers() {
    this._containerService.getContainerUsers()
        .subscribe(
        users => {
            this._containerUsers = users;  <--The array is good here.
        },
        error => {
            this.errorMessage = error;
            if (error.includes("expired")) {
                alert("Login has expired.");
                this._router.navigate(['/login']);
            }
        });
}

getUsers() {
    return this._containerUsers;  <--This returns null.
}

setCurrentUserId(userId: string) {
    this._currentUserId = userId;
    var index = this._containerUsers.findIndex(i => i.login === userId);
    this._currentUserName = this._containerUsers[index].name;
    document.getElementById('userName').innerHTML = this._currentUserName;
    document.getElementById('loggedIn').innerHTML = 'selected.';
}

getCurrentUserId() {
    return this._currentUserId;
}

getCurrentUserName() {
    return this._currentUserName;
}

}

1 个答案:

答案 0 :(得分:0)

我发现最简单的方法是将您的http电话转换为promise,然后使用asyncawait。这就是我在自己的解决方案中所做的:

async populateUsers() {
    this._containerUsers  = await this._containerService.getContainerUsers().toPromise();  
}

getUsers() {
    return this._containerUsers;
}

async ngOninit() {
    await populateUsers();
} 

我非常喜欢这种模式,因为它简化了一切,不需要回调。