我有两个分别名为ProductComponent
和MemberComponent
的Angular 7组件,我想用不同的时间显示它们。例如,我扫描了一个条形码并且该条形码是成员,那么它将显示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
}
});
}
答案 0 :(得分:1)
下面是一个使用ngIf
显示/隐藏的工作示例
ng new project --routing
ng g c barcode
ng g c member
ng g c product
在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 {}
在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() {
}
}
您可以尝试导航到
/barcode/member/uid
或
/barcode/product/pid