Passing data between Service and Component using Angular Binding

I am attempting to show a loading indicator whenever an Http Request is sent. Although I am using Angular's Http Interceptor, the style of the indicator never seems to update.

In my app.component.html, I have included a loading indicator.

  <div [style.display]="visibilityOfLoadingIndicator">
    <mat-progress-bar mode="indeterminate" color="warn" ></mat-progress-bar>
  </div>

Below is the app.component.ts:

export class AppComponent {


  visibilityOfLoadingIndicator = 'none';

  constructor(public loadingIndicatorService: LoadingIndicatorService) {
    this.loadingIndicatorService.getLoadingIndicator()
    .subscribe(visibility => {
      this.visibilityOfLoadingIndicator = <string> visibility;
    });

    }
  }

This is the HttpLoadingIndicatorService.ts:

@Injectable({
  providedIn: 'root'
})
export class LoadingIndicatorService implements HttpInterceptor {


  private display;

  private loadingIndicator: EventEmitter<string>;

  constructor() {
  this.loadingIndicator = new  EventEmitter<string>();
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();
    console.log('Request started');
    this.display = 'block';
    this.updateVisibility(this.display);
    return next.handle(req)
      .pipe(
        finalize(
          () => {
            const elapsed = Date.now() - started;
            const msg = `${req.method} "${req.urlWithParams}"
            in ${elapsed} ms.`;
            console.log(msg);
            this.display = 'none';
            this.updateVisibility(this.display);
          }
        )
      )
      ;
  }



  updateVisibility(state: string) {
    this.loadingIndicator.emit(state);
  }

  getLoadingIndicator() {
    return this.loadingIndicator;
  }


}

The service appears to be functioning correctly based on the console output:

->Request started

->http-loading-indicator.service.ts:24 GET "http://localhost:8080/api/film"
            in 2164 ms.

However, the style of the indicator is not updating. Should I consider creating an Observable?

Answer №1

Definitely! It's important for the component to subscribe to changes from the service in order to notify Angular about any updates.

  constructor(public  authService: AuthenticationService,
              public loaderService: HttpLoadingIndicatorService,
              changeDetectRef: ChangeDetectorRef) {
      loaderService.displayChangeObservable.subscribe(() =>
      { 
          changeDetectRef.markForCheck();
      });
  }

  displayLoader() {
    return this.loaderService.display;
  }

}

Service

@Injectable({
  providedIn: 'root'
})
export class HttpLoadingIndicatorService implements HttpInterceptor {

  private displayUpdateSubject = new Subject<any>();
  public displayChangeObservable = this.displayUpdateSubject.asObservable();

  display = 'none';

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const startTime = Date.now();
    console.log('Request initiated');
    this.display = 'block';
    this.displayUpdateSubject.next();
    return next.handle(req)
      .pipe(
        finalize(
          () => {
            const elapsedTime = Date.now() - startTime;
            const message = `${req.method} "${req.urlWithParams}"
            completed in ${elapsedTime} ms.`;
            console.log(message);
            this.display = 'none';
            this.displayUpdateSubject.next();
          }
        )
      );
  }

}

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 process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

Unable to display a custom image as a check mark on a checkbox

I tried to add some custom CSS to style the images on my checkmark boxes. The goal was to display an image with a checkmark when clicked, but unfortunately, it's not working as expected during testing. For this task, I utilized CSS and HTML from a he ...

Troubleshooting problems with the jQuery 'Add row' function counter

Recently, I encountered an issue with a simple form on my website. The problem arises when I click the 'Yes' radio button and then click 'Add 1 more' multiple times. Instead of adding the desired 4 rows, I end up with around 9 rows. Qu ...

Numerous navigable tabs all on a single page

After following a tutorial on YouTube to create scrollable tabs, I successfully implemented it using Bootstrap 5. However, I'm facing challenges in getting multiple scrollable tabs to function on a single page. Although the tabs and tab-content are fu ...

The style was not applied as the MIME type ('text/html') is not a compatible stylesheet MIME type

Currently, I am in the process of creating a todo-list application. However, I have encountered an issue where the stylesheet is not being applied when accessing localhost:3000/lists/customList. Instead, I am receiving the following error message: "Refused ...

Tips for displaying <p> element upon hovering over a specific area of an SVG image

I created a map and converted it to SVG. I want to display the name of each neighborhood when a user hovers the mouse over it. I'm not sure how to achieve this or how to isolate the specific area of a neighborhood to make changes. Here's a scre ...

Is there a way to dynamically change the height in jQuery/JavaScript?

I am encountering an issue with my embed code where the height changes randomly after a few seconds, depending on certain parameters. Here is an example of the code I am using: $( <embed></embed>) .attr("src", "http://www.bbs.com") ...

Tips for converting a parent class Sprite into a subclass MySprite in Cocos2d-JS

There is a custom class called MySprite that extends Sprite and includes additional methods. var MySprite = cc.Sprite.extend({ ctor:function(){ this._super(); }, doSomethingStrange:function(){ //meow meow } } ); In the game s ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

The function dispatch is not recognized and will be removed from the database. An error will be generated indicating that dispatch is not a valid function

There seems to be an issue with the delete function in Ticket Actions as it is giving an error that dispatch is not a function. The goal here is to enable users to delete specific tickets by clicking on them and also provide an option to edit the ticket. ...

Complete guide on modifying CSS with Selenium (Includes downloadable Source Code)

I am looking to switch the css styling of a website using Python and Selenium. My initial step was to retrieve the current CSS value. Now, I aim to alter this css value. The Python code output is as follows: 0px 0px 0px 270px How can I change it from 0 ...

React - Render an element to display two neighboring <tr> tags

I'm in the process of creating a table where each row is immediately followed by an "expander" row that is initially hidden. The goal is to have clicking on any row toggle the visibility of the next row. To me, it makes sense to consider these row pa ...

Express route fails to wait for Redis server response before moving on

How can I modify the code below to ensure that the res.json(...) command is not executed until all open calls to the Redis client.somecommand(..) have completed successfully? An issue occurs in the code where the client.hmset(uname, { ... } attempt to set ...

Unable to call upon JavaScript code from an external file

Just starting out with Spring and JavaScript! I've put together a JSP file https://i.sstatic.net/XemJ5.png In my first.js, you'll find the following method: function firstmethod() { window.alert("Enter a New Number"); return true; } H ...

Can someone explain why Array.from(classList)[0] is not changing to 'className'?

HTML Design <div class="custom-container color-red"> <h3>Hello, I am a customized container</h3> </div> Javascript Logic let element = document.getElementsByClassName('custom-container')[0]; let clas ...

How to implement PayPal integration in PHP

I am currently working on integrating the paypal payment system into a website dedicated to pet adoption. Initially, I had a basic code structure that was functional. However, after making some modifications and additions to the code, it no longer redirect ...

Display irregularly spaced time samples from a MySQL database on a Google Line Chart using a PHP query

Currently, I am utilizing a Line Chart from Google to display data fetched from a MySQL database involving various variables at different time intervals. Although the sample time is set at 1 minute, there are occasions where some data points are lost (for ...

Learn how to separate strings within an object and add them to an array with JavaScript!

When I receive an object, the quantity of strings differs each time and varies. Object { key_id: 7, key1: "String1, String2", key2: "String1, String2, String3", key3: "String1, String2", key4: "String1, String2"; … } I am lo ...

In the year 2021, eliminate linked documents using mongoose/MongoDB middleware

After extensive research on stack overflow, I attempted various solutions for deleting referenced documents in MongoDB using node.js. Unfortunately, most of them either utilize deprecated methods or simply do not function as expected. Within my applicatio ...

Clear the cache of a query in React Query without having to fetch it again

Within my React app, I have implemented React Query in the following manner: const { data, status } = useQuery(key, queryFunc, { staleTime: 1 * 60 * 1000 }); In order to invalidate a specific key in the cache based on the value of the data, specifical ...