0

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

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

4

1 回答 1

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);
于 2018-04-20T07:04:16.770 回答