【问题标题】:How to implement a loading spinner with a Angular (5) ng-template?如何使用 Angular (5) ng-template 实现加载微调器?
【发布时间】:2018-01-22 15:59:48
【问题描述】:

我有一个结帐页面,用户必须先登录才能继续。 用户已经可以登录。在每种情况下,我都想在组件检测到用户是否登录时显示一个微调器。

check-out.html 代码如下:

<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>

我的结帐组件看起来像:

export class CheckoutComponent implements OnInit {
  private showSpinner = true;

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

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

但总是显示(和),但我只想加载微调器,然后加载#guest 或#authenticated。如何实现?

如果搜索了很多但发现 ngIf 只能采用 if-else 构造。

【问题讨论】:

    标签: angular typescript ng-template


    【解决方案1】:

    当我们要使用微调器时,涉及到三个“组件”

    一项服务

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

    一个组件加载器

    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;
      }
    }
    

    需要显示/隐藏加载的组件、服务或拦截器

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

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 1970-01-01
      • 2018-10-08
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多