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: https://i.sstatic.net/5Myql.png

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

and [2]: https://i.sstatic.net/Wn3Bv.png

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

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Is that possible to prevent the use of the & symbol in Angular 4 HTTP requests?

Using an HTTP request to save data in my database. The code snippet I used is: const form = '&inputdata=' + myinput + '&rf_date=' + rf_date; return this.http.post(this.rootUrl, form, {headers : this.reqHeader}); In thi ...

Using Typescript to pass an interface as an argument to a function that requires a JSON type

Here is an extension related to the topic of Typescript: interface that extends a JSON type Consider the following JSON type: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} The goal is to inform type ...

How are the .map files utilized in angular-cli, and is there a way for ng build to generate these files automatically?

When running ng build with angular-cli, it generates three files: inline.bundle.js vendor.bundle.js main.bundle.js In addition, it also creates a map file for each one. But why? I am wondering if there is a way to customize this process and avoid genera ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

Leveraging async/await in Firebase functions along with the once() method

Recently diving into the world of TypeScript, I've been navigating my way through with relative ease. However, I've encountered a perplexing issue while working with async/await. The problem lies within this code snippet - the 'await' ...

Guide to creating varying component sizes using ReactJS and Styled Components

Is it possible to add variation to my button based on the prop 'size' being set to either 'small' or 'medium'? interface Props { size?: 'medium' | 'small'; } How can I adjust the size of the component us ...

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

Tips for selecting the best className type for material-ui components

Currently, I am integrating material-ui into a react app that is built using typescript. Within the material-ui framework, there is a feature called withStyles which allows styles to be injected into a component through its className. However, I am facing ...

Break free/Reenter a function within another function

Is there a way to handle validation errors in multiple task functions using TypeScript or JavaScript, and escape the main function if an error occurs? I am working in a node environment. const validate = () => { // Perform validation checks... // ...

Tips for invoking TypeScript code from Rust WebAssembly

Currently, I am considering transitioning a slow TypeScript library (jackson-js) to WASM using rust. This particular library has various dependencies, like reflect-metadata for example. These dependencies are already created and accessible on npmjs. The ...

Implementing the withAuthenitcationProps method in all page.tsx files to integrate Amazon Cognito authentication

I have been working on my Next.js app and wanted to share the project structure with you: ├── README.md ├── amplify │ ├── #current-cloud-backend │ ├── README.md │ ├── auth │ ├── backend │ ├── cl ...

Issues arise in TypeScript 5.1.3 with lodash due to type errors involving excessively deep type instantiation, which may potentially be infinite

Recently, I made updates to my Ionic/Angular project and now it is running Angular version 16.1.3 along with TypeScript version 5.1.3. In addition to this, my project also includes the following dependencies: "lodash-es": "^4.17.21", ...

Unlocking the Power of Azure Key Vault with Angular for Securing Your Secrets

Can Azure Key Vault be utilized to retrieve a vault access secret within an Angular application? I am currently building with Azure Active Directory using implicit flow, which means I am developing everything without a backend. Within my Angular project, ...

Exploring the capabilities of UIGrid in conjunction with TypeScript DefinitelyTyped has been a

I've noticed that the latest release of UI Grid (RC3) has undergone significant architectural changes compared to nggrid. I am encountering some problems with the definitelytyped files for nggrid because they are from a different version. Will there ...

Using Ionic 3 to create a list view that includes buttons linked to the items clicked

I need assistance with modifying the button icon in a list layout: <ion-list inset *ngFor="let audio of event.audios; let i = index"> <ion-item> <div class="item-text-center item-text-wrap"> {{audio.fileName}} </div& ...

What is the best way to implement CSS Float in typescript programming?

For a specific purpose, I am passing CSS Float as props. To achieve this, I have to define it in the following way: type Props = { float: ???? } const Component = ({ float }: Props) => {......} What is the most effective approach to accomplish this? ...

How will the presence of @types/react impact the higher-level files in my project?

Here is the structure of my directories vue node_modules src react_app node_modules @types/react package.json ...other file package.json Why does the presence of "@types" in a subdirectory affect the top-level directory? I ...