How to implement a loading spinner with a Angular (5) ng-template?

好久不见. 提交于 2019-12-02 07:34:23

When we want to use a spinner, there are three "components" implicated

A service

export enum loaderCommand { "Begin","End" };

export class LoaderService {
  private loaderSource = new Subject<any>();
  loaderEvent = this.loaderSource.asObservable();

  sendEvent(value: loaderCommand,message?:string) {
    this.loaderSource.next({command:value,message:message});
  }
}

A component loader

export class LoadingComponent implements OnInit, OnDestroy {

  private isAlive: boolean = true;
  constructor(private loaderService: LoaderService ) { }

  ngOnInit() {
    this.dbsService.dbsEvent.pipe(takeWhile(() => this.isAlive)).subscribe((res: any) => {
      if (res.command == loaderCommand.Begin) {
        this.message = res.message ? res.message : "Loading...";
        //do something to show the spinner
      }
      if (res.command == loaderCommand.End)
        //do something to hide the spinner
    })
  }
  ngOnDestroy() {
    this.isAlive = false;
  }
}

A component, service or interceptor that need show/hide the loading

constructor(private loaderService: loaderService ) { }
//when we want to show the spinner
this.loaderService.sendEvent(loaderCommand.Begin,"Hello word");
//when we want to hide the spinner
this.loaderService.sendEvent(loaderCommand.End);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!