How to implement a loading spinner with a Angular

2019-03-03 09:27发布

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 if the users logged in our not.

The check-out.html code looks like:

<div *ngIf="showSpinner">
    <app-spinner></app-spinner>
</div>

<div *ngIf="auth.user | async; then authenticated else guest">
    <!-- template will replace this div -->
</div>

<!-- User NOT logged in -->
<ng-template #guest>
    <div *ngIf="auth.user == null" class="call-to-action">
        login buttons...
    </div>
</ng-template>

<!-- User logged in -->
<ng-template #authenticated>
    payment staps
</ng-template>

My check-out-component look likes:

export class CheckoutComponent implements OnInit {
  private showSpinner = true;

  constructor(public auth: AuthService,
              private router: Router) {
              }

  ngOnInit() {
    this.auth.user.subscribe(user => {
      this.showSpinner = false;
    });
  }
...

But the the (and the) is always displayed, but I want to load only the spinner and then the #guest or #authenticated. How to accoplish?

If searched a lot but find that the ngIf only can take a if-else construction.

1条回答
迷人小祖宗
2楼-- · 2019-03-03 10:01

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);
查看更多
登录 后发表回答