Search code examples
angularrxjsangular-httpclient

How to send a boolean from a http request to a component?(Angular)


I created a program with Angular 7 and i want to catch the http request in a boolean and to transfer it to a component. I tried to use BehaviourSubject with next for this. So the boolean has to be true inside these two functions checkin() and checkOut(). I attached the code. I would appreciate any help. Thanks!

import { Component, OnInit } from '@angular/core';
import { HttpLoadingInterceptor } from '../../../interceptor/http-loading.interceptor';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app',
  templateUrl: './app.html',
  styleUrls: ['./app.scss']
})
export class App implements OnInit {
  subscriptionBlockUI: Subscription;
  blockUIState: boolean;

  constructor(
    private httpLoadingInterceptor: HttpLoadingInterceptor
  ) { }

  ngOnInit() {
      this.subscriptionBlockUI = this.httpLoadingInterceptor.blockUIStateValue().subscribe((blockUIValue: boolean) => {
      this.blockUIState = blockUIValue;
    });
  }

  ngOnDestroy(): void {
    this.subscriptionBlockUI.unsubscribe();
  }

}
import { Injectable } from '@angular/core';
import { BlockUIService } from 'ng-block-ui';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { CompileShallowModuleMetadata } from '@angular/compiler';

export const HEADER_LOADING = 'loadingEnabled';

@Injectable()
export class HttpLoadingInterceptor implements HttpInterceptor {

    readonly blockUiSelector: string = 'http-request';
    private count = 0;
    public blockUIState = new BehaviorSubject<boolean>(false);

    constructor(private uiServ: BlockUIService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.headers.has(HEADER_LOADING)) {
            return next.handle(req);
        }

        this.checkin();
        return next.handle(req).pipe(finalize(() => this.checkOut()));
    }

    public checkin() {
        if (this.count === 0) {
            this.uiServ.start([this.blockUiSelector]);
        } 
        this.count++;
        this.blockUIState.next(true);
    }

    public checkOut() {
        this.count--;

        setTimeout(() => {
            if (this.count === 0) {
                this.uiServ.stop([this.blockUiSelector]);
            }
        }, 10); 
        this.blockUIState.next(true);
    }

    public blockUIStateValue(): Observable<boolean> {
        return this.blockUIState;
    }
}


Solution

  • Okay, if you don't get the value, may be you would want to make blockUIState an Observable via a BehaviorSubject.

    In service.ts

    public blockUIState = new BehaviorSubject<boolean>(false);
    blockUIState$ = this.blockUIState.asObservable();
    

    In component.ts

      ngOnInit() {
          this.subscriptionBlockUI = this.httpLoadingInterceptor.blockUIState$.subscribe((blockUIValue: boolean) => {
          this.blockUIState = blockUIValue;
        });
      }
    

    Edit: previous correction is not working. Try to set a debugger

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.headers.has(HEADER_LOADING)) {
            return next.handle(req);
        }
        debugger;
        this.checkin();
        return next.handle(req).pipe(finalize(() => this.checkOut()));
    }
    

    Because checkin() is only called in this section. please try it.

    Edit: please remove the next.handle(req) from if clause. The code should be for now:

    if (req.headers.has(HEADER_LOADING)) {
        // return next.handle(req);
    }
    
    this.checkin();
    return next.handle(req).pipe(finalize(() => this.checkOut()));
    

    Because, when the condition is true, it will return and the next portion from `this.checkin() is not called.