A guide on showcasing real-time data with Angular's service feature

home.component.ts

<h1>{{ (reportsToday$ | async)}}</h1>
<div echarts [options]="alertsDaily$ | async">
<div echarts [options]="alertsToday$ | async">
<div [onDisplay]="alertsDaily$ | async">

report.component.ts

constructor(private report: ReportService) {}

getReports() {
  this.report.getStatusReport();
}

report.service.ts

  displayAlert$ = new BehaviorSubject(undefined);
  reportsToday$ = new BehaviorSubject(undefined);
  alertsToday$ = new BehaviorSubject(undefined);
  alertsDaily$ = new BehaviorSubject(undefined);

constructor() {}

getStatusReport() {

  loading = {
    today: false,
    daily: false
  };

    this.loading.today = true;
    this.loading.daily = true;

    const severities = ['LOW', 'MEDIUM', 'HIGH', 'URGENT'];
    const reportModules = [
      { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } },
      {
        url: 'application1',
        params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() }
      },
      {
        url: 'application2',
        params: {
          to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
          from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
        }
      },
      {
        url: 'application3',
        params: {
          to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
          from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
        }
      }
    ];

    const promises = applicationModule.map(
      target =>
        new Promise(resolve => {
          this.notificationService
            .getSummary(target.url, target.params)
            .pipe(take(1))
            .subscribe(
              (result: Response) => 
                resolve({ target, result });
              },
              (err: Error) => {
                // return reject(err);
              }
            );
        })
    );

    Promise.all(promises).then(results => {
      const options = this.preConfig;
      const week = this.getWeek();

      results.forEach((res: any) => {
             ....

        if (res.target.url !== '') {
          if (res.target.url === 'application1') {
            ....
            this.loading.today = false;
            this.alertsToday$.next(options.today);
          }else {

            if (res.target.url === 'application2') {
              ...
              ...
              this.loading.daily = false;
              this.alertsDaily$.next(options.daily);
            } else {
              ....
              ....
              this.loading.daily = false;
              this.alertsDaily$.next(options.daily);
            }

          }
       }else {
          this.reportsToday$.next(res.result[0]);
}
    }
   });

}

The issue at hand is the failure to showcase the observable data. Although no errors occur when running the application, the data from

displayAlert$, reportsToday$, alertsToday$ and alertsDaily$
is not displayed.

I opted for using a service because I intend to access it from other components as well.

Is there a way to extract the observable data from the service and exhibit it on the home component?

Answer №1

When working with components, it is important to note that variables cannot be directly accessed from the service. Instead, they should be accessed within the component itself.

Furthermore, in order for values to be properly set, you must subscribe to the values being emitted using .next(). Failing to do so will result in the value not being updated.

Answer №2

It seems like the issue may be coming from new BehaviorSubject(undefined);. Have you tried initializing it as new BehaviorSubject([]); for arrays, new BehaviorSubject(''); for strings, or new BehaviorSubject(0); for numbers?

I'm assuming that you have properly connected the service to the components.

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 are some React component libraries compatible with Next.js 13.1?

I'm exploring Next.js and experimenting with version 13.1 and the new app directory. Is it feasible to accomplish this without sacrificing the advantages of server controls? An error message I encountered states: You're attempting to import a c ...

How come the Angular8 form status registers as VALID even if the input fields are empty?

The following is the structure of the component: export class SchedulerComponent implements OnInit { schedulerForm : FormGroup; constructor(private fb: FormBuilder, private schedulerReportService: SchedulerReportService) { this. ...

Using an object does not result in updated data, while data changes are typically observed when using a variable

In the process of developing a function to update a custom checkbox upon clicking (without resorting to using the native checkbox for specific reasons). Here's the code snippet for the checkbox: <div class="tick-box" :class="{ tick: isTicked }" @ ...

I am continuously encountering an error message saying [$injector:modulerr] while working with AngularJS

I've been reviewing my JavaScript code thoroughly, but I can't seem to pinpoint any major issues. The error message I'm encountering is as follows: Uncaught Error: [$injector:modulerr] Failed to instantiate module careApp due to: Error: [$i ...

Looking for a jQuery function to reload images?

I have a GIF image loading bar animation that I want to reload when the "Reload Image" button is clicked, so that the animation will repeat. //HTML <img src="http://i54.tinypic.com/2qdwtp0.gif" id="load-bar"/> <a href="#" id="reloadImg">Relo ...

Utilizing d3.csv to load CSV data into an nvd3 multiBar Chart demonstration (in JSON format)

I am attempting to recreate a nvd3.js multiBar Chart using my own .csv data. While I have come across similar questions in the past, none of them have provided a solution specific to my current issue. Some suggestions involve utilizing d3.entries, d3.nest, ...

The AngularFireAuth.user observable does not trigger when combined with the withLatestFrom RxJS operator

When using the AngularFireAuth.user observable as the source observable, like in the example below: this.AngularFireAuth.user.subscribe((u) => console.log(u)) everything works fine. However, when I try to include it in the withLatestFrom operator, as s ...

A guide on converting your current Angular app into a "fully strict" application – follow these steps!

I started developing an Angular Application back in Angular 4 and now it has been upgraded to Angular 12. However, during the initial development phase, the strict mode was not enabled. Now that the application is stable and live in production, I am lookin ...

Sharing information in React applications

I'm a beginner when it comes to using javascript and React, so I have a question regarding posting data from within a component. In my scenario, I am utilizing the fetch API for making POST requests. Below is the code snippet I have created: export f ...

Discovering the optimum route within a 2D array given specific limitations using Dynamic Programming

Hey, I have a query related to dynamic programming (dp) that goes like this: Input: A 2D array of numbers Output: The maximum sum of a path from (0,0) to (n-1,n-1) with the following conditions: You can only move down and right i.e. from (A[i-1][j]) t ...

Retrieve the value of a property within the same interface

Is there a way to access an interface prop value within the same interface declaration in order to dynamically set types? I am attempting something like this: export type MethodNames = "IsFallmanagerUpdateAllowed" | "UpdateStammFallmanager& ...

Update the webpage's style by executing an npm command

Looking for a way to use different style sheets (S1.scss and S2.scss) for separate clients using npm commands during application build or with npm start. The app is built with Webpack 2. Any suggestions on how to achieve this customization? ...

Press the button to reveal the hidden Side Menu as it gracefully slides out

I'm interested in creating a navigation menu similar to the one on m.facebook.com, but with a unique animated slide-out effect from the left side of the website. Here's the flow I have in mind: Click a button > (Menu is hidden by default) Men ...

Keep your Vue table continuously updated in real-time

While I have come across similar questions like this and this, my issue presents a unique challenge. I am polling data for a table every second from my REST Api using axios. Despite this, I want the user to be able to freely manipulate (e.g. order, sort, ...

ng-if not working properly upon scope destruction

While working on a isolate scope directive, I encountered an issue. In the link function of this directive, I am compiling an HTML template and then appending it to the body of the document. const template = `<div ng-if="vm.open"></div>`; body ...

Submit data via POST method on the modified URL

I need assistance with modifying the data of a URL and making a POST request to it. The URL in question is as follows: http://domanin.com/search-result/?start=06%2F08%2F2017&end=06%2F09%2F2017&room_num_search=1&adult_number=1&children_num= ...

Javascript: Insert a class declaration post loading of the page

When working with native web components, it is necessary to be able to add class definitions after the page has loaded, especially when new types of components are dynamically added to the DOM. EDIT: Here's a brief explanation: In order to define we ...

vue-form and vue-material are not compatible with each other

In my experience, using a Vue form on a regular HTML <input> element allows validation to work as expected. However, when I switch to using the <md-input> element, the validation no longer functions and an error message is displayed: Element ...

CSS Attribute Selector Wildcard Capture Tool

Suppose I have the following HTML structure: <div class="tocolor-red"> tocolor </div> <div class="tocolor-blue"> tocolor </div> <div class="tocolor-green"> tocolor </div> <div class="tocolor-yellow"> tocolor ...

Is it necessary to include a back button when navigating through paginated tables?

Within my AngularJS application, I have implemented pagination on the user list page. This allows me to retrieve ten users at a time from the server, with each click loading another set of ten users on a new page. The user details are presented in a tabl ...