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
209 views
in Technique[技术] by (71.8m points)

javascript - Angular + Rxjs operator - show loader if api not completed within 5 sec show toastr and hide loader

Actually we are trying to avoid blocking user to do other operation while file upload in progress.

how can i show toastr and hide the loader if api is not completed with in 5 sec using rxjs in angular.

uploadFile() {
  this.service.uploadFile(data)
    .pipe(
      //i am looking for operator which will wait 5 sec if and then hide the loader and show the toastr
    )
    .subscribe(() => {
      this.toastr.success('file uploaded successfully');
      this.loader.hide();
    })
}
question from:https://stackoverflow.com/questions/65844474/angular-rxjs-operator-show-loader-if-api-not-completed-within-5-sec-show-toa

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

1 Reply

0 votes
by (71.8m points)

you can create loading service like this:

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

@Injectable({
  providedIn: 'root',
})
export class LoadingService {
  private isLoading = new Subject<boolean>();
  constructor() {}

  public start(isHideImmediately: boolean = false) {
    this.isLoading.next(true);
    if (isHideImmediately) {
      setTimeout(() => {
        this.complete()
      }, 5000);
    }
  }
  public complete() {
    this.isLoading.next(false);
  }

  getLoadingStatus(): Observable<boolean> {
    return this.isLoading.asObservable();
  }
}

and each time you call api you can start loading in start loading method by default after 5s loading is closed

your code:

uploadFile() {
  this.loadingService.start();
  this.service.uploadFile(data).subscribe(() => {
    this.toastr.success('file uploaded successfully');
    this.loadingService.complete();
  })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...