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

What is the best way to filter by enum value in Typescript?

If I define an enum as follows: export enum Status { InProgress = 0, Completed = 1, Cancelled = 2 } and have a class that references the enum: import { Status } from "./Status"; export class TaskDto { public name: string = null; public c ...

Adjust validation message and minimum value when radio button is altered in Angular application

Seeking a way to dynamically set a validation message and minimum value based on a radio button selection. Currently, there are two radio buttons for either 9 or 18 holes, each with a corresponding input (used in a golf handicap calculator app). The goal i ...

When building with Angular using the "ng build" command, the JavaScript file names are altered

I'm currently learning Angular and I've noticed that when creating a new project with Angular CLI, files like runtime.js, polyfills.js, main.js, styles.css are generated. However, after running the ng build command, similar files can be found in ...

The FormControl is currently presenting ",required(control)" within its value field

Upon loading my form, the default values in the input fields are set to: ,required(control) { return isEmptyInputValue(control.value) ? { 'required': true } : null; } The template structure of my form is as follows: <form [formG ...

Is there a way to stop Material UI from dulling the color of my AppBar when using dark mode in my theme?

When I use mode: "dark" in my Material UI theme, it causes the color of my AppBar to become desaturated. Switching it to mode: "light" resolves this issue. This is how my theme is configured: const theme = createTheme({ palette: { ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Setting the [required] attribute dynamically on mat-select in Angular 6

I'm working on an Angular v6 app where I need to display a drop-down and make it required based on a boolean value that is set by a checkbox. Here's a snippet of the template code (initially, includeModelVersion is set to false): <mat-checkbo ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

What kind of error should be expected in a Next.js API route handler?

Recently, I encountered an issue with my API route handler: import { NextRequest, NextResponse } from "next/server"; import dbConnect from "@/lib/dbConnect"; import User from "@/models/User"; interface ErrorMessage { mess ...

Unable to navigate to a page called "meeting" in NextJS 13 due to issues with router.push not functioning correctly

import { Input, Button } from '@nextui-org/react'; import router from 'next/router'; import { SetStateAction, useEffect, useState } from 'react'; const SignIn = () => { const [errorMessage, setErrorMessage] ...

Enrich TypeScript objects by incorporating additional properties beyond the ones already present

If I have an expression and want to add extra properties without repeating existing ones, how can I achieve that? For instance, if the expression is a variable, it's simple to include additional fields (like adding field e): const x = { a: 1 }; cons ...

Importing the isPropertyUpdated method in Angular 4

My challenge lies in utilizing the isPropertyUpdated function within Angular 4. However, I have encountered a roadblock as Angular 4 does not facilitate deep imports. An example of an import that fails to work on Angular 4 is: import {isPropertyUpdated} ...

const error = new TypeError(`${calculateRelativePath(cwd, fileName)}: Skipping emission of file`);

Hey there! I have a typescript code snippet that looks like this: import { getConnection } from "typeorm"; import { GraphQLClient } from "graphql-request"; import got from "got"; import database from "./utils/database&quo ...

Diverse Options in the Form Generator

Is there a way to save both the value of "member.text" and "member.id" in "this.fb.group" at the same time? I want to display the text value in a table but also send the id value to my service. form: FormGroup = this.fb.group({ result: this.fb.array( ...

What is the best method for embedding my token within my user entity?

Currently, I am working on implementing a "forgot password" feature in my application. The idea is that when a user requests to reset their password, they will receive a token via email that expires after two hours. To prevent the generation of multiple to ...

What causes TypeScript to convert a string literal union type to a string when it is assigned in an object literal?

I am a big fan of string literal union types in TypeScript. Recently, I encountered a situation where I expected the union type to be preserved. Let me illustrate with a simple example: let foo = false; const bar = foo ? 'foo' : 'bar' ...

What is a more efficient way to write nested subscribe in Angular?

I am a beginner with RxJS and I'm interested in learning how to write clean code using it. I currently have a nested subscription that I've been trying to refactor without success. firstMethod() { this.testMethod(name) console.log(this.curren ...

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...

Encountering a multitude of challenges when attempting to seamlessly integrate aframe into an angular2 project, especially when incorporating unit tests

I'm encountering issues with integrating aframe 0.7.0 effectively into my angular 4.3.6 (angular-cli 1.0.0) project. The error messages I am receiving include: Chrome 61.0.3163 (Windows 10 0.0.0) LOG: '%cA-Frame:warn %cPut the A-Frame <script ...

What steps do I need to take to mark an Angular form field as invalid using manual input?

I need help with a login form validation issue. When a user enters invalid credentials, I want to mark both the email and password fields as invalid and display a message indicating that the login failed. Can anyone guide me on how to achieve this using an ...