Creating a list with axios in the ngOnInit lifecycle hook

I have a feature where I need to populate objects fetched from the backend.

ngOnInit() {
        this.source.load(this.myService.findAll());
    }

Within myService, I am using Axios to retrieve data from the backend. I can confirm that the data is successfully reaching the frontend.

public findAll(): any {
        axios.get('http://localhost:8080/api/getAll')
            .then(function (response) {
                console.log(response.data);
            })
            .catch(function (error) {
                console.log(error);
            })
    }

How can I invoke the service from the component to obtain an array of objects?

Answer №1

ngOnInit does not support async functionality, so you will need to execute your method in a fire-and-forget manner. In the code snippet below, I am using fetch instead of axios. However, the concept should be similar for axios.

If you are aware of the exact array you are expecting, you can replace Promise<any> with Promise<MyObject[]>. Make sure to add as MyObject[] after .json()

// Angular Component
ngOnInit() {
  (async () => {
    const data = await this.myService.findAll();
    this.source.load(data);
  })();
}

// MyService Class
public async findAll(): Promise<any> {
  try {
    const response = await fetch('http://localhost:8080/api/getAll');
    if (!response.ok) {
      throw new Error("Failed to fetch data");      
    }

    return await response.json();
  } catch (error) {
    throw new Error("Failed to fetch data");
  }
}

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

A data type labeled as 'undefined' needs to include a method called '[Symbol.iterator]()' which will then return an iterator

I've been working on converting my reducer from JavaScript to TypeScript, but I keep encountering a strange error that I can't seem to resolve. The issue arises when I attempt to use ellipsis for array deconstruction in the reducer [...state.mess ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

The navigator.geolocation.watchPosition call did not return any available position information

I offer a service that monitors the position of devices: getLocation(opts): Observable<any> { return Observable.create(observer => { if (window.navigator && window.navigator.geolocation) { window.navigator.geolocat ...

Problems with the duration of Shadcn Toasts (Inspired by the react-hot-toast library)

Within a 13.4 Nextjs project (app router), utilizing Typescript and TailwindCSS. I am currently exploring the usage of toasts provided by the remarkable shadcnUI Library, which draws inspiration from react-hot-toast while adding its own unique flair. Imp ...

What is the best way to implement useAsync (from the react-async-hook library) using TypeScript?

Currently, I am utilizing react-async-hook to retrieve API data within a React component. const popularProducts = useAsync(fetchPopularProducts, []); The fetchPopularProducts() function is an asynchronous method used to make API calls using fetch: export ...

The ongoing ESLint conundrum: Balancing between "Unused variable" and "Unknown type" errors when utilizing imports for type annotations

I've encountered a linting issue and I need some guidance on how to resolve it. Here's the scenario - when running $ yarn lint -v yarn run v1.22.4 $ eslint . -v v6.8.0 With plugins vue and @typescript-eslint, I have the following code in a .ts ...

Is there a way for me to program the back button to navigate to the previous step?

I am currently developing a quiz application using a JSON file. How can I implement functionality for the back button to return to the previous step or selection made by the user? const navigateBack = () => { let index = 1; axios.get('http ...

Limiting the use of TypeScript ambient declarations to designated files such as those with the extension *.spec.ts

In my Jest setupTests file, I define several global identifiers such as "global.sinon = sinon". However, when typing these in ambient declarations, they apply to all files, not just the *.spec.ts files where the setupTests file is included. In the past, ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

Is it possible for Typescript to automatically infer object keys based on the value of a previous argument?

Currently, my goal is to create a translation service that includes type checking for both tags and their corresponding placeholders. I have a TagList object that outlines the available tags along with a list of required placeholders for each translated st ...

Struggling with TypeScript errors when using Vue in combination with Parcel?

While running a demo using vue + TypeScript with Parcel, I encountered an error in the browser after successfully bootstrapping: vue.runtime.esm.js:7878 Uncaught TypeError: Cannot read property 'split' of undefined at Object.exports.install ...

Challenges faced with the Nativescript Software Development Kit

I am currently working on a Nativescript app with Angular and using a JSON server. However, I am facing some errors when I try to run 'tns run android' or 'tns doctor' commands. × The ANDROID_HOME environment variable is either not se ...

When you import objects in Typescript, they may be undefined

I have a file called mock_event that serves as a template for creating an event object used in unit testing. Below, you can find the code snippet where this object is initialized: mock_event.ts import {Event} from "../../../models/src/event"; im ...

Best Method for Confirming Deletion in Data Table with Shadow and UI

I have a query regarding the Shadcn/UI - Data Table component. In my case, I am working with a list of users where each row has a delete button in the last column. Upon clicking the delete button, a confirmation dialog pops up. Currently, I am implementi ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

What is the best way to add a repository in Nest.js using dependency injection?

I am encountering an issue while working with NestJS and TypeORM. I am trying to call the get user API, but I keep receiving the following error message: TypeError: this.userRepository.findByIsMember is not a function. It seems like this error is occurring ...

Challenges with Type Casting in TypeScript

Upon reviewing a specific piece of code, I noticed that it is not producing any compile time or run time errors even though it should: message: string // this variable is of type string -- Line 1 <br> abc: somedatatype // lets assume abc is of some ...

Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query: Excuse me, I am new to Typescipt & RxJS. I have this JSON data: [ { "ID": "", "UEN": "", "Name": "", "Address": "", "Telephone&quo ...

Encountering a NullInjectorError in Angular while utilizing dynamic module federation when importing a standalone component along with

My main goal is to develop a shell application acting as a dashboard without routing, featuring multiple cards with remote content (microfrontend standalone component). I have been following a tutorial that aligns closely with my requirements: . The reas ...