Leveraging a Service Property Initialized by Callback Function Across Different Components in Angular

When I try to access the myData property of a DataService in my DataComponent, it is undefined due to waiting for callback. How can I properly utilize and access this data?

export class DataService {
  public myData;

  constructor(private http: HttpClient) {
    this.load().then((data) => {
      this.myData = data
    })
  }

  load() {
    return new Promise((resolve) => {
      this.http.get('https://reqres.in/api/users').subscribe(
        (res: any) => {
          console.log(res.data)
          resolve(res.data)
        },
        (error) => {
          console.log(error);
        }
      )
    })
  }
}
export class DataComponent implements OnInit {
  constructor(private dataService: DataService) {
    this.prepareData();
  }

  prepareData() {
    console.log(this.dataService.myData)
  }

  ngOnInit(): void {
  }
}

To view the source code, click on this link: https://stackblitz.com/edit/angular-ivy-kbpdpo

Answer №1

You may encounter a race condition due to the asynchronous nature of this function.

A successful solution can be found here: https://stackblitz.com/edit/angular-ivy-vf3llg

For more information, consider looking into https://angular.io/guide/http

In my experience, I prefer having services return raw data and handling manipulation separately. However, if necessary, you can access the response as demonstrated in the updated example.

This question and answer may very well be a duplicate of the following...

What are pipe and tap methods in Angular tutorial?

Answer №2

When using the load() method, keep in mind that it operates asynchronously. This means that it may take up to 2 hours for a response to be returned and processed by your callback function. However, if you are requesting data synchronously with myData, you are expecting an immediate response which will not be possible due to the asynchronous nature of the load() method.

In order to ensure that you wait for the response before proceeding, consider removing the myData field and subscribing to the data within the component instead. Alternatively, you can create a BehaviorSubject and emit values to the component once they are available.

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

Fetching information using JSON for creating a RangeArea Chart with CanvasJS

I'm currently working on creating a range area chart with CanvasJS and PHP to fetch data from a database. After setting up the php script to retrieve values from the DB, here's what I have: <?php header('Content-Type: application/json&a ...

How to extract the text content of an element using XPath in Selenium?

I have a setup that looks like this : <div class="content"> <h3 class="faq">Joocey</h3> Locked Bag 4005 <br> 6/78 William Street <br> Sydney NSW 2000 <br> Customer Ca ...

Program that duplicates text to clipboard upon clicking on the text

Hey there, I have a query regarding the script provided below: function copyElementText(id) { var text = document.getElementById(id).innerText; var elem = document.createElement("textarea"); document.body.appendChild(elem); ...

Angular 2 Authentication Service powered by Reactive Extensions

I am currently working on a login form component that includes the following: login.component.ts ngOnInit() { this.authenticationService.loginAttempt .subscribe(() => this.onSuccess(), err => this.onError(err)); } login(credentials) { ...

What is the best way to invoke a Service from a Directive in AngularJS?

Every time a user clicks, a directive is triggered to change the icon for adding to their favorite list. View: <div class="col col-33"> <i class="icon ion-ios-heart-outline" favorite="place[0].objectId" on-icon="ion-ios-heart-outline" off-ic ...

Is there a way to showcase a "waiting" signal on a webpage as the web server is executing the HTTP request?

Context - My web application has a functionality that requires several seconds to process a request. Inquiry - What is the best way to show a "waiting" indicator, such as a spinner, to the user after they trigger the request, until the server responds wit ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

Fetch information from MySQL, create a new row for each data entry

Currently, I am working on a project for my school that involves retrieving student works from a database. For the homepage of my project, I have set up 10 divs to hold the data returned from a query. The reason I preset these divs is because I only need ...

Enhancing your scheduling capabilities with Kendo UI Web Scheduler - Dynamically managing resources dataSource

I've been attempting to dynamically change the resources dataSource in my Scheduler, but unfortunately, the changes I am making are not reflecting in the Scheduler interface. Here is how I have set up the scheduler: $("#scheduler").kendoScheduler ({ ...

Guide to sorting a JavaScript array using a filter object

Using a dynamically generated filter object from a multi-search UI component, the data needs to be filtered based on the criteria. Once the user initiates a search, the data will be filtered accordingly. Below is an example of the filter object and sample ...

The alignment of Bootstrap v4.5 checkbox is limited as it cannot be positioned horizontally or vertically when placed next to an input field

As stated in the title: Bootstrap's checkbox is having trouble aligning Horizontally or Vertically when placed next to an input. Error Displayed: https://i.sstatic.net/hNHpm.png I have experimented with various solutions, but none have provided sat ...

Is there a more efficient method for crafting this Angular Testing code?

Currently, I am trying to enhance my knowledge of Angular testing. However, I am struggling to locate reliable resources that can guide me on the correct approach to take. My dilemma lies in my spec file where I am utilizing a function setDashboardGreetin ...

Is it possible for web browsers to set a timeout on an XmlHttpRequest while it is still active?

When dealing with asynchronous XMLHttpRequests that take a long time to retrieve data from the server, I am searching for a way to abort them. Setting a timeout before sending the XHR is not feasible due to the length of these requests. Although calling X ...

Angular routerLink causes ngOnInit to be triggered only once

I have come across numerous questions similar to mine, however, the majority are linked to params. The answers provided did not aid in resolving my specific issue. Essentially, the problem I am facing is as follows: After a user logs in, their username is ...

Changing the default font size has no effect on ChartJS

I'm trying to customize the font size for a chart by changing the default value from 40px to 14px. However, when I set Chart.defaults.global.defaultFontSize to 14, the changes don't seem to take effect. Below is the code snippet for reference. An ...

Adding dynamically generated HTML elements and binding them to an AngularJS controller is a powerful capability that

As I dive into learning angularJS, I am facing a challenge in determining the best architecture for my project. My single page app is designed in such a way that the URL must always remain unchanged; I do not want users to navigate beyond the root route. T ...

showcasing real-time webcam information within an HTML web application

I have successfully integrated my webcam data live into my web application using the following code snippet. The live feed from my webcam is now visible on the webpage. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta ...

Utilizing ngModel within a ngFor iteration

Utilizing ngModel within an ngFor loop to extract data from a dropdown menu goes as follows: <div *ngFor="let group of groups"> <select [(ngModel)]="selectedOption"> <option *ngFor="let o of options" ...

The variable 'FC' has been defined, however it is not being utilized. This issue has been flagged by eslint's no-unused

After running eslint, I encountered a warning stating that X is defined but never used for every type imported from react or react-native. For example, this warning appeared for FC and ViewProps (refer to the image below). Below is my .eslintrc.js configu ...

What is the reason behind Angular5 making an API call upon pressing F5 in the browser?

As a newcomer to angularjs (using v5), I am currently exploring routing. The routing functionality is in place, but I have noticed that data only loads when the f5 key is pressed. For instance, on my sign-in page, clicking the login button triggers an API ...