The response from the Http GET request in the Angular web service app was delayed

I am currently working with Angular CLI version 8.3.2 and Node version 10.16.3 on win32 x64. My project involves integrating an Angular frontend with a .NET backend. The frontend communicates with the backend API to retrieve a list of messages using an HTTP GET request, and then displays these messages in the browser.

Here is the implementation of the getMessage function in the WebService service component:

public async getMessage() {
    await this.http.get<Message[]>(this.BASE_URL + '/Messages').subscribe(
        result => {
            if (result) {
                this.updateCollection(result);
            }
        },
        error => console.error(error)
    );
}

Additionally, here is the MessagesComponent that invokes the webService to retrieve the messages:

export class MessagesComponent {
    constructor(private webService: WebService) { 
        console.log("messages has " + webService.messages.length + " entries");
        webService.getMessage();
        console.log("messages has " + webService.messages.length + " entries");
    }
}

Although both functions execute without any errors, the issue lies in the delayed execution of the getMessages function. Despite being called within the constructor of the MessagesComponent, it appears to fetch the data only after the constructor, resulting in an empty message list upon rendering the page. I have attempted invoking getMessage without using async/await, however, the behavior persists. How can I ensure the messages are retrieved promptly without latency?

Answer №1

Retrieve data as an observable from a service function.

public fetchData() {
    return this.http.get<Data[]>(this.BASE_URL + '/Data')
        .pipe(
            tap(val => this.updateCollection(result)),
        );
}

Instead of calling the function in the constructor, it is recommended to call it in the ngOnInit method.

export class DataComponent implements OnInit {
    constructor(private dataService: DataService) {}

    ngOnInit(){
        this.dataService.fetchData()
            .subscribe(
            result => {
               // perform actions
            },
            error => console.error(error)
        );
    }
}

Answer №2

My usual approach is to have the service handle the observable return. Here's an example:

export class MessagesComponent {
    messages: Message[];
    constructor(private webService: WebService) { 
        webService.getMessage().subscribe(messages => {
            this.messages = messages;
        });
    }
}

However, it's recommended to move this logic into the ngOnInit method in the end.

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

Guide on setting the number of records to display on each page using ngx pagination in Angular 4

Successfully integrated ngx pagination in my Angular 4 project and it's functioning well. However, I'm facing a challenge in displaying the number of records per page as (Showing: 1 - 10 / 25). I've attempted to solve it but unfortunately ha ...

Setting up personalized colors for logging in Angular 2 with ng2-logger

Recently, I decided to try out a new tool called ng2-logger to improve the visualization of my console logs. https://www.npmjs.com/package/ng2-logger However, I've noticed that the colors it generates are random. Is there a way for me to choose spec ...

Differences between Typescript Import and JavaScript import

/module/c.js, attempting to export name and age. export const name = 'string1'; export const age = 43; In b.ts, I'm trying to import the variables name and age from this .ts file import { name, age } from "./module/c"; console.log(name, ...

Make sure that the input for a function is a valid key within a specific interface, and that the corresponding value in the interface is

I'm a beginner in TypeScript and I've hit a roadblock with this issue. Despite searching extensively, I haven't found a solution yet. My goal is to create a well-typed sorting function that takes two parameters: an array of objects and the ...

Guide on maintaining Spring Security authentication across Angular front-end

Following the initial feedback on my query, I made adjustments to my Spring Security setup and successfully logged in and accessed a test endpoint using Postman. However, when the same endpoint is called by Angular post successful login, the request fails, ...

Angular and Bootstrap do not support margin styles

While working with Angular 5 and Bootstrap, I have encountered an issue with using inline styles for margin. The template I am using is as follows: @Component({ selector: "dynamic-container-component", template: ` <div styl ...

Visibility in classes can shift once a new file is imported

Currently, I am encountering a puzzling issue in my angular2 project using typescript. In my main.ts file, which contains a component along with some imports at the start of the file, there is a custom type class (let's call it TypeFoo) located in mod ...

Why does my export function get executed every time the TextInput changes?

Hey there, here is my React and TypeScript code. I'm wondering why the console.log statement gets called every time my text field changes... export default function TabOneScreen({ navigation, }) { const [out_1, set_out1] = useState('' ...

Leveraging the expand function for pagination through recursive invocations

I am currently working on retrieving data from a third party API that necessitates manual management of paging by keeping track of the number of records retrieved versus the total number of records available. In attempting to handle this, I experimented w ...

Load components dynamically and place them in a flexible position based on the context

UPDATE (After gaining a better understanding of the issue): I'm trying to display a component based on where the user clicks (specifically, which table row). Using ng2-smart-table, I've encountered an issue where there isn't a suitable sele ...

changing the dropdown options and button label when a value is inputted into the input field

When a user inputs a value, the following requirements should be met: The dropdown menu must be disabled, and the only available option should be 'Pending' The button should display the title "SAVE FEES" If the user does not input a value but c ...

What is the best approach to perform type checking on a function that yields varying types depending on the values of its

Currently, I am facing a challenge with a function that takes an argument and returns a different type of value depending on the argument's value. For instance: function foo(arg: 'a' | 'b') { if (arg === 'a') { ret ...

What is the step-by-step guide for implementing an access limiter on an interface

When attempting to modify the access level on an interface in Typescript, I encountered an error stating 'cannot appear in type member.' After removing the access limiter on the interface and implementing it, I tried changing the access limiter o ...

Display Angular elements within dynamically injected HTML

I am facing an issue with my Angular 15 application. I have a component called FatherComponent, which receives HTML content via an API and injects it into its template using innerHTML: <div [innerHTML]="htmlContent"></div> The proble ...

Typescript Array does not adhere to correct data type

Why does the code below fail to transpile when pushing a new instance of class B into an array that is typed as only accepting instances of class A? class A {}; class B {}; const arr: A[] = []; arr.push(new B()); ...

Struggling to implement the proper authentication method with API in Ionic

Having an API for the login, but being new to Ionic is causing difficulty in creating the correct method for the login process. The service file is located here: providers/restapi/restapi.ts import { HttpClient } from '@angular/common/http'; im ...

What is the evaluation process for conditions like someItem?.someField==somevalue in Angular?

Let's consider a simple condition in the markup: someItem?.someField==somevalue What does this mean? Is it equivalent to someItem!=null && someItem!=undefined && someItem==somevalue So essentially, if someItem is undefined, the ent ...

Changing JSON names to display on a webpage

I am looking to modify the name displayed in a json file for presentation on a page using ion-select. mycodehtml ion-select [(ngModel)]="refine" (ionChange)="optionsFn(item, i);" > <ion-option [value]="item" *ngFor="let item of totalfilter ...

Issue with typing in subscription encountered in Typescript RXjs version 6.6.0

Have you attempted using the code snippet below? const data = new Data() data.subscribe({ next: (value) => {}, error: (value) => {}, complete: (value) => {}, }); Encountering this error: Compilation failed. sr ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...