Imported angular module doesn't work the first time a route is visited, but it works in the subsequent visits

Viewed 43

I have a simple Loader Module hosted in a private npm repository. This module only intercepts http calls and displays a css loader. The code is simple: it has a public api that exports the module and a component. The module has an http interceptor that calls a service which sets a variable isLoading.

The component code is split into three files, as usual (ts, html and scss).

loader.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { LoaderService } from '../service/loader.service';

@Component({
  selector: 'loader',
  templateUrl: './loader.component.html',
  styleUrls: ['./loader.component.scss']
})
export class LoaderComponent implements OnInit {

  public isLoading: boolean;

  constructor(private loaderService: LoaderService) { }

  ngOnInit(){
    this.loaderService.isLoading.subscribe(status => this.isLoading = status);
  }
}

loader.component.html

<div *ngIf="isLoading" class="overlay">
  <div class="loader center-block"></div>
  <p class="wait">
    <strong>Wait...&nbsp;&nbsp;&nbsp;</strong>
  </p>
</div>

The loader.component.scss file defines the loader, overlay and wait css classes (not shown for brevity).

The interceptor code is here:

@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
  constructor(private loaderService: LoaderService) {}

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    this.loaderService.show();
    return next.handle(request).pipe(finalize(() => this.loaderService.hide()));
  }
}

And finally, the service code:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoaderService {
  public isLoading: Subject<boolean>;

  constructor() {
    this.isLoading = new Subject<boolean>();
  }

    show() {
        this.isLoading.next(true);
    }
    hide() {
        this.isLoading.next(false);
    }
}

This module is imported at the app.module.ts of an application and declared in the imports array of the decorator.

The application has some routes with lazy load feature modules.

The loader module is used at the app.component.html file, as follows:

<loader></loader>
<router-outlet></router-outlet>

The problem: the loader does not work the first time we visit a route, but it works if we click the previous button at the browser or we click to go back to homepage or any other way I tested visiting a route twice or more. Otherwise, it doesn't work.

I tried to find similar questions, I tried to see the order of css imports, I also tried to analise the loader module, the import order, but no clue about what is happening.

0 Answers
Related