如何以不同的指定时间显示不同的组件?

How can I display different components with a different specified amount of time?

我有两个不同的 Angular 7 个组件,名为 ProductComponentMemberComponent,我想用不同的时间显示它们。例如,我扫描一个条码,如果条码是会员,那么它会显示MemberComponent 10 秒,而如果我扫描一个产品条码,它会显示ProductComponent 30 秒。我怎样才能做到这一点?

我已经尝试在两个组件上使用函数 setTimeout,指定时间间隔,但它似乎影响了其他组件。

当我扫描会员条码和扫描产品条码时,ProductComponent只显示 10 秒而不是 30 秒。



这是我的 member.component.ts

代码
ngOnInit() {
  this.route.params.subscribe(params => {
    this.barcode = params['id'];

    this.loadMember();

    setTimeout(() => {
      this.router.navigate(['']);
    }, 10000); // I wan't to display this component for 10 seconds
  });
}



这是我的 product.component.ts

代码
ngOnInit() {
  this.route.data.subscribe(result => {
    this._json = result.json;
  });

  if (this._json == null) {
    this.route.params.subscribe(params => {
      this.barcode = params['id'];

      if ( this.barcode === '' ) {
        return;
      } else {
        this.loadProduct();

        setTimeout(() => {
          this.router.navigate(['']);
        }, 30000); // I wan't to display this component for 30 seconds
      }
  });
}

下面是使用 ngIf

show/hide 的工作示例

1。创建项目

ng new project --routing

ng g c barcode

ng g c member

ng g c product

2。添加带有参数的路由

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BarcodeComponent } from './barcode/barcode.component';

const routes: Routes = [
  { path: 'barcode/:type/:id', component: BarcodeComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

3。使用 ngIf

将 Product 和 Member 组件添加到 Barcode 组件

barcode.component.html

<app-product *ngIf="scanType == 'product'"></app-product>
<app-member *ngIf="scanType == 'member'"></app-member>

barcode.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-barcode',
  templateUrl: './barcode.component.html',
  styleUrls: ['./barcode.component.scss']
})
export class BarcodeComponent implements OnInit {

  scanType: string = ""

  constructor(
    private route: ActivatedRoute
  ) {
    this.route.params.subscribe(params => {
      this.scanType = params['type'] || ''
      let time = (params['type'] == "member") ? 10000 : 30000
      setTimeout(()=> {
        this.scanType = ""
      }, time)
    })
  }

  ngOnInit() {
  }
}

4。测试

你可以尝试导航到

/barcode/member/uid

/barcode/product/pid