Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javascript - Why doesn't next () notify subscribers? rxjs

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

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

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...