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

问题描述 投票:1回答:1

我有两个不同的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
      }
  });
}
angular typescript countdown angular-components
1个回答
1
投票

下面是一个使用ngIf显示/隐藏的工作示例

1. Create Project

ng new project --routing

ng g c barcode

ng g c member

ng g c product

2. Add route with params

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. Add Product and Member component to Barcode component with ngIf

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

你可以尝试导航到

/barcode/member/uid

要么

/barcode/product/pid

© www.soinside.com 2019 - 2024. All rights reserved.