Angular component unable to retrieve array data from Angular service

I've developed an Angular service that serves as a middleman for fetching data from a database. Here's the code:

export class WebService {
constructor(private http: Http, private datePipe: DatePipe) {
    this.getStatsbyDate(this.datePipe.transform(new Date(), 'dd-MM-yyyy'));
}
statsModel = {
    date: this.datePipe.transform(new Date(), 'dd-MM-yyyy'),
    answeringMachine:0,
    hangUp: 0,
    conversations: 0
};
getStatsbyDate(date) {
    this.http.get(this.BASE_URL + '/stats/' + date)
      .subscribe(
        res => {
            this.btnsOnResponse = true; 
            this.statsModel = res.json(); 
            // console.log(this.statsModel);                              
        },
        err => {
            console.log("Couldn't fetch data")
        }
    );
}

In one of my Angular components, I'm attempting to access the retrieved data like so

export class FusionChartsComponent implements OnInit {
  constructor(private webService: WebService) {}
  ngOnInit() {
     console.log(this.webService.statsModel.answeringMachine);
  }
}

I'm perplexed by this behavior and seeking advice on resolving it.

Answer №1

To implement the changes outlined in the documentation provided at the following link: https://angular.io/guide/http, it is recommended to move the subscribe function to the component. By doing so, you can easily add any necessary code within the subscribe block.

fetchStatsByDate(date) {
    this.http.get(this.BASE_URL + '/stats/' + date)
      .pipe(
        tap(res => {
            this.responseReceived = true; 
            this.statsData = res.json();                            
        }),
        catchError(err => console.log("Failed to fetch data"))
    );
}

export class FusionChartsComponent implements OnInit {
  constructor(private webService: WebService) {}
  ngOnInit() {
     this.webService.fetchStatsByDate().subscribe(
         data => {
             console.log(data);
             console.log(this.webService.statsModel.machineStatus);
     });
  }
}

EDIT

If you require the service to maintain its data for sharing across different components, consider implementing the following approach:

@Injectable()
export class MovieService {
    private moviesUrl = 'api/movies';
    private movies: IMovie[];

    constructor(private http: HttpClient) { }

    getMovies(): Observable<IMovie[]> {
        if (this.movies) {
            return of(this.movies);
        }
        return this.http.get<IMovie[]>(this.moviesUrl)
                        .pipe(
                            tap(data => console.log(JSON.stringify(data))),
                            tap(data => this.movies = data),
                            catchError(this.handleError)
                        );
    }
}

Each component can then subscribe to the service like this:

this.movieService.getMovies().subscribe(
    (movies: IMovie[]) => this.movies = movies,
    (error: any) => this.errorMessage = <any>error
);

The initial call to the service will trigger an HTTP request to retrieve the data, which is then stored privately. Subsequent calls will receive the already fetched data without additional requests.

Subscribing close to the UI element is considered a "best practice" by most developers as it ensures that the code within the subscribe block only executes when the required data is available.

An example demonstrating this concept can be found here: https://github.com/DeborahK/MovieHunter-communication/tree/master/MH-Take4

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

The Angular 7 Router seems determined to lead me straight to the 404 error page

In my Angular 7 project, I am facing an issue with the routing. I have integrated the <router-outlet></router-outlet> directive within a component called navigation. Whenever I click on a link to navigate to a different path, the router initial ...

Exploring the Magic of Angular 2 in Visual Studio 2015

Struggling to develop a sample application has been a major challenge for me. Whether it's just trying to create a simple "hello world" program or rewriting the Heroes app from Angular.io, I seem to hit roadblocks every time. Is there anyone out there ...

The type of JSX element attribute `[...]` cannot be a combination of multiple types

When attempting the codes below in Typescript 2.1: // address.tsx ... interface Address { street: string; country: string; } interface CanadianAddress extends Address { postalCode: string; } interface AmericanAddress extends Address { zipCode: s ...

How can you retrieve the keys of an object that conforms to an interface?

In the following demonstration, we have two objects - KEYS and KEYS2. When importing KEYS in index.ts, autocomplete suggestions are available for K1 and K2 because KEYS does not adhere to an interface. On the other hand, with KEYS2, autocomplete is not pr ...

How can I integrate React-Router Link as a component within Material-UI using Typescript?

Hey everyone, I've encountered an issue while trying to utilize Material UI's component prop to replace the base HTML element of a component. Error: The error message reads: Type 'Props' is not generic. This problem arises from the fo ...

Oops! Your file couldn't make it to Firebase Storage in Angular

I have been working on creating an upload function to upload files or images to my Firebase database storage. I have ensured that the correct API key is placed in the environment.ts file and imported into app.module.ts as AngularFireModule.initializeApp(en ...

Ways to identify scroll occurrences within a mat-sidenav-container

Is there a way to detect the scroll event in Angular Material 2 when using mat-sidenav-container? I'm trying to call a method in my component whenever a user scrolls, but with mat-sidenav-container the scroll event doesn't work on the window any ...

Adding local images to Excel can be easily accomplished using Office Scripts

Hello, I've been attempting to replace Excel cells that contain image filepaths with the actual images themselves. I found an example in Office Scripts that shows how to insert images with online URLs but doesn't mention anything about inserting ...

Can we limit the return type of arrow function parameters in TypeScript?

Within my typescript code, there is a function that takes in two parameters: a configuration object and a function: function executeMaybe<Input, Output> ( config: { percent: number }, fn: (i: Input) => Output ): (i: Input) => Output | &apos ...

Whenever I am building a React application, I encounter a bug that states: "node:fs:1380 const result = binding.mkdir()"

Whenever I try to enter the command: create-react-app my-app --template typescript I keep encountering this error message: node:fs:1380 const result = binding.mkdir( ^ Error: EPERM: operation not permitted, mkdir 'D:\ ...

Exploring Facebook Graph API response with Angular 2 Mapping

I am using HTTP calls to access the Graph API in order to retrieve posts from a Facebook page. Here is the code snippet that fetches an array of posts: let url = 'https://graph.facebook.com/15087023444/posts?fields=likes.limit(0).summary(true),comme ...

Uploading Multiple Files to a REST API Using Angular 6's Reactive Form

Looking to create a file uploader in Angular 6 using a reactive form. Once all files are selected, there will be an upload button to start uploading the files. The issue I'm facing is that I can't access all the files from the component without u ...

Convert JSON data to an array using Observable

My current task involves parsing JSON Data from an API and organizing it into separate arrays. The data is structured as follows: [ {"MONTH":9,"YEAR":2015,"SUMAMT":0}, {"MONTH":10,"YEAR":2015,"SUMAMT":11446.5}, {"MONTH":11,"YEAR":2015,"SUMAMT":5392 ...

The Angular Material Table Collapse feature offers dynamic collapsing similar to jQuery Datatable

Is there a way to improve the appearance of my Angular Material Table, especially on mobile? https://i.stack.imgur.com/sZXPP.png The current display of my Angular Material Table is not aesthetically pleasing when viewed on mobile devices. https://i.stack ...

Angular 10: A Guide to Utilizing RouterModule

I'm working on enhancing one of my components by adding a button that will navigate the page to a different component : <input type="button" value="Shops List" [routerLink]="['shops-list']" class="btn&qu ...

Error message 2339 - The property 'toggleExpand' is not recognized on the specified type 'AccHeaderContextProps | undefined'

When utilizing the context to share data, I am encountering a type error in TypeScript stating Property 'toggleExpand' does not exist on type 'AccHeaderContextProps | undefined'.ts(2339). However, all the props have been declared. inter ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

The module "vue-final-modal" does not have an exported member named 'ModalsContainer'

"vue-final-modal": "^3.4.11" -> update to "vue-final-modal": "^4.4.5", "vue": "^3.3.4", using composition API, TypeScript, and Vite Operating System: Windows Upon running the build command, I ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Tips for transferring JSON information from a perl script to an angular controller on a local level

Summary: I am looking for a way to utilize a service similar to Angular's http service, but locally on my machine without the need for a server to be running. Currently, I am encountering this error message: Access to XMLHttpRequest at 'file:C:/ ...