How to retrieve an array of objects using Angular 2 service?

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

}

Answer №1

An effective approach I have discovered is to transform your http requests into a promise, and then utilize async and await. This method has proven successful in my own implementations:

async fetchUserData() {
    this._userContainer = await this._userService.getUserData().toPromise();  
}

retrieveUsers() {
    return this._userContainer;
}

async initialize() {
    await fetchUserData();
} 

I find this technique very convenient as it streamlines the process without requiring callbacks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for storing headers in NODE.JS?

Recently started learning NODE.JS Looking for some guidance. When I try to execute the command below: npm install --save express-handlebars I encounter the following error message: + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

Identifying unwanted values to be sought in a string array using VBA

In the program below, we are comparing the values in range "B"&t to an array given in x(1). I am also looking to include negative values so that negative values in that range can be detected during the comparison. However, I'm unsure of how to enter a ...

Find the mean of three numbers stored in an array of objects

I am currently working on a school assignment that requires me to develop a function for calculating the average mark of 3 students using an existing object in an array. Below, you can see the array and function that I have been working on as part of this ...

Query the Mongoose database to fetch all records that are not listed in the array field of the same collection

I am facing a challenge with my Post schema. Within this schema, there is an array field that can contain other posts as replies. My goal is to retrieve all the documents that are not referenced in any post's replies field. Essentially, I want to extr ...

If the checkbox is selected, include an anonymous email in the field and conceal the field

I am looking to enhance my Feedback form by providing users with the option to submit feedback anonymously. However, my CMS requires both Email and Name fields to be mandatory. To address this, I am considering adding a checkbox that, when selected, auto ...

Mastering the art of utilizing defer/async attributes in script tags effectively

When I add the "defer" attribute to all external js files, Owl Carousel fails to load and shows an error that "$" is not defined. However, if I remove the defer attribute from the script tag, everything works fine without any errors. Unfortunately, I am un ...

Can Typescript automatically determine the return type based on the function argument value?

How can Typescript be utilized to deduce the return type from the valueType parameter instead of using overloads? type ValueType = 'integer' | 'string' | 'number' | 'date' | 'dateTime' | 'boolean&apos ...

What is the best way to send a variable value to a React component?

Currently, I'm utilizing the https://github.com/and-who/react-p5-wrapper library to integrate p5.js into my React project. I'm interested in finding a solution to pass a value generated within the p5 Sketch file back into React. Specifically, I ...

The ace.edit function is unable to locate the #javascript-editor div within the mat-tab

Having trouble integrating an ace editor with Angular material Error: ace.edit cannot locate the div #javascript-editor You can view my code on StackBlitz (check console for errors) app.component.html <mat-tab-group> <mat-tab label="Edito ...

What steps do I need to take in order to turn my code into a versatile

My code is displayed below. I am looking to refactor it into a reusable component, but I'm not sure where to begin. How can I achieve this? Any guidance would be greatly appreciated. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris auct ...

Retrieve information using the useEffect hook on a server-side rendered webpage

I am currently working on a project using React JS and Next JS. The page is dynamic, utilizing getStaticPaths and getStaticProps to fetch most data on the server side for rendering. However, there are certain pieces of data that require a token stored in l ...

Ionic - numerical age selector control

Currently working on a hybrid mobile app and ran into a specific issue. I'm in the process of adding new items to my left side menu, including an age number spinner component (min:18, max:65). After searching through various sources and Ionic documen ...

Strip out the script tag from the data received in the AJAX response

I'm currently developing a single-page application using jQuery. The entire HTML pages are sent to the browser as an AJAX response. $.post(url, function (data) { $("#resp").html(data); $("#resp").find("script").each(function (i) { ...

What is the best way to paginate a dynamically updated data table using AJAX in Laravel?

I'm currently facing an issue with rendering a Blade template in Laravel. The template includes an HTML table populated with data fetched via AJAX, and I need to implement manual pagination using Laravel's LengthAwarePaginator. The main Blade fi ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Harnessing the power of VUE.js: Exploring the versatility of V-bind with Array and

I've encountered an issue with an app I'm currently working on. In my project, I am utilizing Vue.js to create the front-end and attempting to apply two classes to a div within a v-for loop. The first class is bound with a filter that functions ...

Fix React/Typescript issue: Exported variable conflicts with name from external module

I am encountering a perplexing issue when using React with Redux and Typescript. The error message I am receiving is unfamiliar to me, and I am unsure how to resolve it. The error states: Exported variable 'rootReducer' has or is using name ...

Attempted to display a Google Map within a lightbox, but encountered difficulties in getting it to

I've copied and pasted my code below. It may contain references to Google or Lightbox being undefined, but I'm unsure how to integrate them into the code provided. My goal is to display a Google map within a Lightbox popup, but so far I have been ...

Having trouble implementing showLoaderOnConfirm feature in SweetAlert2

I’ve been encountering some difficulties with implementing the showLoaderOnConfirm feature using sweetalert2 and ngSweetAlert for AngularJS. Although the code below runs smoothly and without any errors, I’m not seeing any loading animation. The alert ...