I am facing an issue with my Angular 2 service component. It is responsible for populating an array of objects, and I need to access this array from other components in the program. However, the getUsers() method always returns null as shown in the code snippet below.
How can I modify getUsers() so that it correctly returns the populated array from populateUsers()?
The Service Component's code snippet:
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 successfully populated here.
},
error => {
this.errorMessage = error;
if (error.includes("expired")) {
alert("Login has expired.");
this._router.navigate(['/login']);
}
});
}
getUsers() {
return this._containerUsers; <--This currently 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;
}
}