The initial Get request does not receive data upon first attempt

In the process of developing an Angular project, I am faced with the task of retrieving data from my backend by making requests to an API. However, before the backend can fetch the required data, certain parameters must be sent through a post request. Once the data is obtained and passed to the getCar() method, various data handling functions are immediately executed.

Upon building my project, it initiates a post Request followed by a get Request to the backend. Unfortunately, the get request is triggered before the post request is completed, causing the get request to return null data. Consequently, this leads to TypeErrors in the handling methods that expect valid data. Reloading the page resolves this issue as the proper data is then retrieved.

The objective now is to ensure that the data is fetched successfully on the initial request, requiring the getCar() method to wait until the post request is fully processed.

Here is the code snippet from my component where the services are invoked:

ngOnInit(): void {
    this.postUrlData();
    this.getCar();    
}

postUrlData(){
    this.route.queryParams.subscribe(params => {
      this.urlData = {
        vin : params['vin'],
        dealerId: params['dealerid']
      };
    })
    
     this.apiService.postURLData(this.urlData).subscribe();
}

getCar(){
    this.apiService.getCertainCar().subscribe( data => {
      this.carData = data;
      console.log(data);
      this.filltechDetails();
      this.fillcarEquipment();
      this.fillCarDetails();      
    });
}

Below are the api-services utilized:


@Injectable({
  providedIn: 'root'
})

export class ApiServiceService {

 constructor(private http: HttpClient) { }

   getCertainCar(): Observable<any>{
      return this.http.get(this.serverUrl+'/car')
   }

   postURLData(urlData:any):Observable<any>{
     return this.http.post(this.serverUrl+"/urlData",urlData);
   }
}

Answer №1

It's important to remember to call the get method once the post request has been completed. For instance, you can handle this in subscribe as shown below:

ngOnInit(): void {
    this.submitPostRequest();
}

submitPostRequest(){
    this.route.queryParams.subscribe(params => {
      this.postData = {
        vin : params['vin'],
        dealerId: params['dealerid']
      };

    })
    
    this.apiService.sendPostData(this.postData).subscribe(() => {
      this.getData();
    });   
  }

getData(){
    this.apiService.fetchSpecificData().subscribe( data => {
      this.dataReceived = data;
      console.log(data);
      this.displayTechDetails();
      this.showCarEquipment();
      this.renderCarDetails();
      
    });   }

Furthermore, ensure that before calling this.apiService.sendPostData(), the variable this.postData is already defined. Otherwise, it should be initialized within the queryParams.subscribe() function to guarantee its availability. Alternatively, you can retrieve this.route.snapshot.queryParams, which is simply an object and not an observable.

Answer №2

In my opinion, a more efficient approach would be to implement a resolver that fetches your data prior to the page loading. This way, the necessary parameters and data will be readily available for your subsequent API call without any risk of encountering undefined data.

For more information on how to set up a resolver, you can visit: https://www.digitalocean.com/community/tutorials/angular-route-resolvers

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

After a recent deployment, the Angular PWA hosted on a NestJS server experiences unexpected crashes

I have set up an Angular PWA (version 11) on a NestJS (version 7) server. However, after each new deployment, the PWA crashes because the browser attempts to fetch a JavaScript file that no longer exists and then redirects to the root site (html): main.945 ...

Testing TypeScript using Jasmine and Chutzpah within Visual Studio 2015

I am new to unit testing in AngularJS with TypeScript. I have been using jasmine and chutzpah for unit testing, but I encountered an error "ReferenceError: Can't find variable: angular". My test file looks like this: //File:test.ts ///<chutzpah_r ...

Retrieve user information by their unique user ID from a MongoDB database using a Node, Express, and TypeScript API

Currently, I am working on a Node JS and Express with TypeScript API project. In this project, I need to retrieve data stored by a specific user from MongoDB based on their user ID. This is a snippet from my DataRouter.ts: router.get('/:userId', ...

Leveraging Angular's capability to import files directly from the assets

I recently installed a library via npm and made some modifications to one of the modules. python.js If I delete the node_modules folder and run npm install, I am concerned that I will lose my changes. Is there a way to preserve these modifications by mov ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

Receiving NULL data from client side to server side in Angular 2 + Spring application

I'm currently working on a project that involves using Angular 2 on the client side and Spring on the server side. I need to send user input data from the client to the server and receive a response back. However, I'm encountering an issue where ...

The functionality of ngModel seems to be malfunctioning when used within select options that are generated inside

I'm currently working on dynamically adding options to an HTML select element within a for loop. I am using [(ngModel)] to get the selected option, but initially no option is pre-selected. Here's a snippet of the code: <table align="center"& ...

Dropdown element with PrimeNG adorned with a span

I am trying to create a simple form with text inputs and dropdowns. I have successfully implemented the textInput, but I am struggling with the dropdowns. Below is the code that I have so far: <div class="p-grid p-dir-col p-offset-2"> ...

Leveraging the unique operator with an observable

I've been attempting to eliminate duplicates from my observable by using .distinct(), but it doesn't seem to be working as expected. There are no errors showing either... this.settingsService.getGuruQueries().subscribe(queries => { of<an ...

Tips for refreshing tab body data in Angular Material when switching between tabs

Check out this example code snippet Main Controller <mat-tab-group id="report"> <mat-tab label="Quiz"> <div class="demo-tab-content"> <app-quiz></app-quiz> </div> </mat-tab> <mat-tab label="Exam"> <di ...

How can I integrate a timer into an Angular carousel feature?

I have put together a carousel based on a tutorial I found on a website. Check out the HTML code for my carousel below: <div class="row carousel" (mouseover)="mouseCheck()"> <!-- For the prev control button ...

Loop through a FormArray containing FormGroups

I'm struggling with the functionality of my form array containing form groups. My goal is to loop through the form array and display the input fields within each form group. However, when I use addExercise(), the new form group that I add to the arra ...

.Net Core receives the method name instead of the parameter value passed by TypeScript

Can someone explain why the code is passing "getFullReport" as the eventId instead of the actual value while making its way to the .Net Core 3.1 side? Prior to the call, I double-checked with a console.log to ensure that eventId holds the correct ID I am ...

Exploring Angular 2: How to Retrieve the Value of a Radio Button

How can I retrieve the value of the radio button that is clicked in app.component.html from within app.component.ts? app.component.html <div class="container"> <div class="row"> <div class="col-sm-3 well" style="width: 20%"> ...

What is the correct way to utilize Global Variables in programming?

Having trouble incrementing the current page in my pagination script to call the next page via AJAX... In my TypeScript file, I declare a global variable like this; declare var getCurrentPage: number; Later in the same file, I set the value for getCurren ...

The issue persists with react-hook-form and Material UI RadioGroup as the selected value remains null

Having trouble with RadioGroup from Material UI when using react-hook-form Controller. I keep getting a null selected value, even though my code seems right. Can you help me figure out what's missing? import * as React from "react"; import { ...

Redirecting on the server side in Angular 2

I am currently studying Angular 2 and attempting to develop an application using Angular with Spring. In a traditional J2EE MVC application, the client sends a request, the server processes it, and then redirects to another page. The decision to redirect ...

Building a resolver to modify a DynamoDB item via AppSync using the AWS Cloud Development Kit (CDK)

After successfully creating a resolver to add an item in the table using the code provided below, I am now seeking assistance for replicating the same functionality for an update operation. const configSettingsDS = api.addDynamoDbDataSource('configSet ...

I prefer not to permit components to receive undefined values

When using swr, the data type is IAge| undefined. I want to avoid passing undefined to AgeComponent, so I need the age type to be strictly IAge. Since AgeComponent does not allow undefined values, I am facing an error stating that 'IAge | undefined&ap ...

When utilizing useRef and useCallback in React, the output is visible in the console log but does not appear on the page

When working with API data, it's important to remember that the extraction process is asynchronous and the state may not be available at certain times. To handle this situation, we can utilize useCallback. However, even after successfully logging the ...