如何使用Angular(5)ng-template实现加载微调器?

时间:2018-01-22 15:59:48

标签: angular typescript ng-template

我有一个结帐页面,用户必须先登录才能继续操作。 用户可以登录。在每个场景中,当组件检测到用户是否登录时,我想显示一个微调器。

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结构。

1 个答案:

答案 0 :(得分:2)

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

服务

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