Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make a loading screen with an observable notifying when https requests finish but when I use next (false) to notify subscribers it doesn't notify

loading.service.ts

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';

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

  loading$ = new BehaviorSubject<boolean>(true);
  activeRequests: number = 0

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.activeRequests >= 0) {
      this.activeRequests++
      this.loading$.next(true)
    }

    return next.handle(req).pipe(
      finalize(() => {
        this.activeRequests--;
        this.loading$.next(true)
        if (this.activeRequests === 0) {
          this.loading$.next(false)
        }
      })
    )

  }

}

loading.component.ts

import { AfterViewInit, ChangeDetectorRef, Component, ComponentRef, ElementRef, OnDestroy, OnInit } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { LoadingService } from 'src/app/services/loading.service';

@Component({
  selector: 'app-loading',
  templateUrl: './loading.component.html',
  styleUrls: ['./loading.component.css']
})
export class LoadingComponent implements OnDestroy, OnInit {

  loadingSubscription: Subscription;

  constructor(
    public loadingService: LoadingService,
    private elementRef: ElementRef,
    private changeDetectorRef: ChangeDetectorRef
  ) {
  }

  ngOnInit(): void {
    this.elementRef.nativeElement.style.display = 'none'
    this.loadingSubscription = this.loadingService.loading$
      .subscribe(
        (status: boolean) => {
          console.log('status', status)
          this.elementRef.nativeElement.style.display = status ? 'block' : 'none'
          this.changeDetectorRef.detectChanges()
        }, (err) => {
          console.log('err', err)
        }
      )
  }

  ngOnDestroy(): void {
    console.log('unsubcribe')
    this.loadingSubscription.unsubscribe()
  }

}

ignore: It looks like your post is mostly code; please add some more details.It looks like your post is mostly code

question from:https://stackoverflow.com/questions/65623512/why-doesnt-next-notify-subscribers-rxjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
325 views
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...