Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs:

"ERROR TypeError: Cannot read property 'get' of undefined"

public apiCall(mints:number){
   console.log("from setInterval"); 
//  console.log("api called");
//  this.refInrvl=setInterval(()=>{  
      this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(resp=>{
        this.storeD=resp;
      }); 
  //  },3000)
  }
  public refreshSearch(){
    console.log(this.refMints);
    this.setIntvl();

  }
  public refreshList(refMints:number){
    //this.refMints=refMints;
    console.log("Sel Number",this.refMints);
    this.setIntvl();
  }
  public setIntvl(){
  this.refInrvl=setInterval(this.apiCall,(this.refMints*300*60),this.refMints);
  }

Answer №1

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class DataService {
baseUrl: string;
constructor(private http: HttpClient) {
    this.baseUrl = 'https://jsonplaceholder.typicode.com/posts';
}

public fetchData(): Promise<any> {
    return this.http.get<any>(this.baseUrl).toPromise();
}

To handle the promise, inject the service in any component's constructor and resolve the promise:

async getData() {
    await this.dataService.fetchData().then(res => console.log(res)).catch(err => console.log(err));
}

For better runtime performance and to handle unpredictable behavior of timed functions, it is recommended to use setTimeout or setInterval within the component itself.

refreshResponse(time: number) {
    setTimeout(async () => {
        await this.dataService.fetchData().then(res => console.log(res)).catch(err => console.log(err));
    }, time);
}
console.log(refreshResponse(3000));

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

Error in MatSort implementation - Argument cannot be assigned

I'm having trouble figuring out how to implement the Mat-Sort functionality from Angular Material. When I try to declare my variable dataSource, I get the following error: Argument of type 'Observable' is not assignable to parameter of type ...

The object's value may be 'undefined' after utilizing a switch case to ensure it is not undefined

Before I encountered the error Object is possibly 'undefined'.ts(2532) at testObject["x"], I had used case "x" in testObject. Why did this happen? Should I create my own type guard for it? interface TestObject { a?: number; ...

When an Angular application is built in Electron and a div is printed, a blank window is

After developing an Angular application, I decided to build it in Electron. Surprisingly, everything was working perfectly fine until I encountered an issue with printing a specific div. Whenever I click the print button, a blank window opens up in Elect ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

Having trouble with @viewChild not activating the modal popup and displaying an error message stating that triggerModal is not a function in

I am facing an issue where the click event is not being triggered from the parent component to display a Bootstrap 3 modal. I am getting the following error: ERROR TypeError: this.target.triggerModal is not a function This is what I have done so far: Pa ...

Error: Invalid connection string for ELF Lambda detected

Having an issue with a lambda function that connects to a remote MongoDB on an EC2 instance using TypeScript. While I can connect to the database locally, there is an ELF error when running in lambda. It seems to be related to mismatched binaries of npm pa ...

Angular transforming full names to initials within an avatar

What is the best way to convert names into initials and place them inside circular icons, like shown in the screenshot below? I already have code that converts the initials, but how do we create and add them inside the icons? The maximum number of icons di ...

Guide on making a Mapped Type in TypeScript using dynamic generic parameters

I am working with an object that contains one or more PreparedStatement. I am looking to create a general type definition for this object. Is there a way to achieve this in code? type PreparedRequest<Input, Result> = { input: Input; result: Resul ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

Having difficulty retrieving an angular file from a location outside of the asset folder

I'm encountering issues with a small project that is meant to read a log and present it in table format. Here is the outline of the project structure: project structure Within the LOG directory, I should be able to access motore.log from my DataServi ...

Cannot compile Angular 4 Material table: Encountering unexpected closing tag

Currently, I am working on an Angular 4 Project that involves using Material. The main task at hand is to implement a table from Angular Material. However, the issue I am facing is that the table does not compile as expected. Here's the HTML code sni ...

Issue with Filtering Function in Kendo Angular 2 Grid

I have recently started incorporating the Kendo Grid with Angular 2 by following the guidelines in this tutorial: http://www.telerik.com/kendo-angular-ui/components/grid/data-binding/. However, I am facing a challenge as I am unable to locate the filteri ...

Retrieve data from a table within an Angular component

Struggling with the ng2-smart-table library, I am facing challenges in passing values entered in the edit line to a custom component: Refer to the code snippet below for passing Maximum and Minimum Temperature values to the SmartTableEditorFunctionsCompon ...

Change to a different text field without the need to press the tab key by utilizing

I have set up three different input boxes and I want to know how to switch directly to the next text box without having to press the tab key on the keyboard. The values are stored in a variable called newStringPin. <input type="text" style="width: 38px ...

Error message "Cannot find children property on type IntrinsicAttributes & RefAttributes<unknown>" occurring in a React component due to a Typescript issue

Issue: The specified type '{ children: string; severity: string; sx: { width: string; }; }' is not compatible with the type 'IntrinsicAttributes & RefAttributes'. The property 'children' is missing in the type 'Intri ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Utilizing props in styled-components: A beginner's guide

I am trying to pass a URL to a component so that I can use it as the background image of the component. Additionally, I need to check if the URL is empty. Component: <BannerImg/> CSS (styled): `const BannerImg = styled.img` background-image: url( ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

Guide to creating jest unit test for an observable variable exclusively utilized in a template resulting in the error "Property 'pipe' of undefined cannot be read"

Seeking help with creating unit tests for an Angular component that utilizes a constructor and observable variable in the HTML template. Below is the code snippet I am having issues with: voice-summary.component.ts export class VoiceSummaryComponent { v ...