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

前端 未结 1 1179
旧时难觅i
旧时难觅i 2021-01-29 01:18

I\'ve a checkout page where the user has to login before he can proceed. The user can be logged on already. In every scenario I want to show a spinner when the component detects

1条回答
  •  遥遥无期
    2021-01-29 01:30

    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();
      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);
    

    0 讨论(0)
提交回复
热议问题