In Angular, the data retrieved from the API will only appear on the page once it has been manually

Recently, I started working on an Angular project and encountered a problem with data display after each component routing. Initially, the data is not displayed until the page is reloaded. You can see the issue in the screenshots:

[![After reload][2]][2].

and [2]:

The service code snippet is as follows:

import { Injectable, SimpleChange } from '@angular/core';
{ Add more unique content here }

And here is the corresponding component.ts code:

import { Component, OnInit } from '@angular/core';
import{UserService} from './user.service';
{ Add more unique content here }

If anyone has a solution to this issue, please assist me. Your help is greatly appreciated.

Answer №1

James, it would be beneficial for your service to return observables that you can subscribe to in the component. If you need to manipulate the response in the service, consider using "tap". For example:

NOTE: The purpose of using map is to transform the response. If no transformation is needed, do not use it.

ListAllUsers() {
   // Ensure that you use "return"
   return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
            .pipe(tap(response => {
               ..work with the response here..
               ..similar to what you have in the subscribe method...
             }

In your component:

// Make sure to assign this.Userlst within the subscribe function
this.UserService.ListAllUsers().subscribe(_=>{
    this.Userlst=JSON.parse(sessionStorage.getItem('userlist'));
}

NOTE: If you don't want the value to persist between sessions, storing it in SessionStorage may not be necessary.

Update regarding storage in SessionStorage. If we want the service to return data like userarray, we should utilize "map" to transform the data.

ListAllUsers(): Observable<any>{ 
   // Indicating that an Observable will be returned
        return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
            .pipe(
            .map((result: any) => {
                // The mapping process can be as complex as required
                this.userList.push(result);
                this.userData = this.userList[0].response;
                var status: any;
                const userarray:any=[]; 
                for (let i = 0; i < this.userData.length; i++) {
                    // Using a ternary operator instead of if statements
                    const status=(this.userData[i].status == "True")?"Active":"Inactive";
                    this.userkeypair = {
                        "id": this.userData[i].id, "name": this.userData[i].fullName, "email": this.userData[i].emailId, "account": this.userData[i].relatedAccount,
                        "status": status
                    }
                    userarray.push(this.userkeypair);
                }
                // Simply returning the transformed value
                return userarray;
            });
    }

In our component:

this.UserService.ListAllUsers().subscribe(response=>{
    this.Userlst=response
}

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

Is there a TypeScript rule called "no-function-constructor-with-string-args" that needs an example?

The description provided at this link is concise: Avoid using the Function constructor with a string argument to define the function body This might also apply to the rule missing-optional-annotation: A parameter that comes after one or more optiona ...

Is there a feature similar to notifyWhenNoOutstandingRequests in Angular 2?

In my experience, test frameworks like Arquillian have utilized this method to determine when the DOM is ready for inspection with Angular 1. I am curious if there is a similar approach for accomplishing this in Angular 2? ...

Integrating Auth0-js with the usePostMessage functionality

Encountering difficulties when compiling an Angular application that incorporates the auth0-js package. The code utilizes the method renewAuth(options: RenewAuthOptions, callback: Auth0Callback<any>): void;, yet it seems to be causing issues as the p ...

TypeScript abstract class generics: `Class<?>` type

When working with TypeScript, I often utilize a Java-like type called Class: interface Class<T = void> { new(...args: any[]): T; } Unfortunately, this type doesn't seem to be compatible with abstract classes: abstract class Bar {} class ...

Is there a way to trigger a custom event from a Web Component and then intercept it within a React Functional Component for further processing?

I'm facing an issue with dispatching a custom event called "select-date" from a custom web component date picker to a React functional component. Despite testing, the event doesn't seem to be reaching the intended component as expected. Below is ...

ExitDecorator in TypeScript

Introduction: In my current setup, I have an object called `Item` that consists of an array of `Group(s)`, with each group containing an array of `User(s)`. The `Item` object exposes various APIs such as `addUser`, `removeUser`, `addGroup`, `removeGroup`, ...

Concealed URL - Navigation with Angular 2 Routing

Is it possible to conceal the URL when using window.open()? Alternatively, can the Angular2 router be utilized to open the URL in a fresh tab? I am familiar with the method of concealing the URL during routing by using this.router.navigate(["/Pages"], { s ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

Having difficulty launching a TypeScript Node.js application using ts-node and pm2

I have a node app built with TypeScript and it works fine with nodemon, but when I try to move it to the server using PM2, I encounter errors. I've searched GitHub and StackOverflow for solutions, but nothing has worked for me so far. Any help would b ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

A single image path utilized for both development and production stages during the Angular build process

I am struggling to determine the correct path for my images to work seamlessly on both development and production environments. Currently, I can only get them to display properly on my local development server. However, when I use the command ng build --pr ...

What are the steps to locally set up the Angular.dev website?

The latest version of angular.dev has just been launched and made available as open source. I'm eager to set it up on my local machine, but I'm facing issues running yarn smoothly within the Node 18 container. Here's what I've attempted ...

show the stored value inside the useRef variable

One of my challenges involves a variable const prediction = useRef<any>(null); A button triggers a function that updates the variable's value: function showResult() { classifier.current.classify(capture, (result) => { ...

Angular EventEmitter fails to emit event

I am currently working with an Angular vertical stepper (using Angular Material) consisting of separate components for each step, with a parent component calling all these child components. My challenge is in passing data between the parent and child compo ...

Utilizing a single Observable across multiple Pages and Components through a Service

I am attempting to subscribe to the same Observable multiple times, but it is not working as expected. I have a Provider that retrieves the Observable from an AngularFirestore object. Here is my provider: @Injectable() export class MyProvider { private ...

"Enable email delivery in the background on a mobile app without relying on a server

I am currently in the process of developing a mobile app using Ionic. One feature I would like to incorporate is sending an email notification to admins whenever a post is reported within the app. However, I am facing challenges with implementing this succ ...

Encountering issues with deploying an Angular 8 website using a specific configuration

My current project is built on Angular 8, and I am in the process of publishing it locally before deploying it. When running the build step, I specify an environment name called internalprod: src ├───app ├───environments │ environme ...

The 'DOCUMENT' module (imported as 'i23') could not be located within '@angular/platform-browser'

During my upgrade from Angular version 7 to 8, I encountered an error when building the project even though I am not using DOCUMENT. It seems like something is causing this issue that I am overlooking. I have thoroughly checked all the files and confirmed ...

Could I potentially pause and wait for a subscription in Angular?

I'm looking to display a list of posts similar to this: Post List In order to indicate which post is favorited by a user, I need to retrieve data from two different collections in my MongoDB database. The ngOnInit function in my post-list.component.t ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...