angular - 检测 Angular 组件是否“正在使用”
问题描述
我有两个使用 Observable.interval 在后台运行代码的角度组件。当给定事件发生时,每个组件都应该播放声音,但只有当前“可见”的组件才应该真正播放声音。组件基于当前路由“可见”。
现在发生的事情是两个组件都在播放声音并且听起来已经损坏。我的想法是我应该检测一个组件是否“可见”,而不是在这种情况下为该组件播放声音。
有没有办法检测一个组件是否正在使用,或者我应该有另一种方法来处理这个要求来播放声音?
代码,我已经修剪了不相关的代码以节省空间
ViewUpdateService提供组件订阅的 observable。
@Injectable()
export class ViewUpdateService {
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
this.notifier = isPlatformBrowser(this.platformId)
? Observable.interval(250)
: Observable.empty();
}
notifier: Observable<any>;
}
ListComponent是第一个需要在给定时间点发出声音的组件
@Component()
export class ListComponent implements OnInit {
private soundHandler(): void {
if(!this.triggerEventOccurred)
return;
if(this.shouldPlaySoundIfVisible)
this.kerching.play();
}
// ... removed to preserve space ...
constructor(private viewUpdateService: ViewUpdateService) {}
ngOnInit(): void {
this.dataService.getList()
.subscribe(l => this.handle(l));
this.viewUpdateService.notifier
.subscribe(t => this.soundHandler());
}
}
DetailComponent是第二个需要在不同时间点发出声音的组件
@Component()
export class DetailComponent implements OnInit {
private soundHandler(): void {
if(!this.triggerEventOccurred)
return;
if(this.shouldPlaySoundIfVisible)
this.kerching.play();
}
// ... removed to preserve space ...
constructor(private route: ActivatedRoute,
private viewUpdateService: ViewUpdateService) {}
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => {
const id = params.get('id');
if(!id)
return Observable.empty();
return this.dataService.get();
})
.subscribe(s => this.handle(s));
this.viewUpdateService.notifier
.subscribe(t => this.soundHandler());
}
}
使用角度路由使组件可见
export const DrawRoute: Route = {
path: 'draw',
children: [
{ path: ':id', component: DetailComponent, },
{ path: '', component: ListComponent, },
]
};
解决方案
非常抽象,因为您没有提供太多细节。
将播放的声音提取到单独的组件中,提取Observable.interval
到单独的服务中。
component1
在您的and中使用您的声音播放组件component2
(您可以通过 切换其可见性*nfIg
)并使用您Observable.interval
的声音播放组件。
声音播放组件可以接收参数,告诉它哪个父级正在使用它,因为和@Input() contextType
的声音应该不同。component1
component2
[根据您添加的上下文更新]
由于声音播放显然是两个组件的共同点,我将在单独的地方提取它,在使用和soundPlayingComponent
的父级中使用它,并让这两个组件根据将播放的适当声音暴露给父级。ListComponent
DetailsComponent
Output() playSound:EventEmitter<whateverParamsYouNeed>
推荐阅读
- vuejs3 - Vuejs 3 Composition Api:将道具数据传递给ref时出错
- python - 如何方便地将此字符串转换为列表?
- angular - Angular HTTP 拦截器自定义预检
- ios - flutter ios app在testflight模式下显示白屏?
- python - 存储为数据框列中列表的向量的 Seaborn 回归线图
- azure-data-factory - 寻找有关执行复杂 csv 到 json 数据流转换的建议
- plotly-dash - jupyterlab 中的 Dash 有时会因“127.0.0.1 拒绝连接”而失败
- pseudocode - 计算数组中存在多少“倒计时”序列
- xcode - 在 Xcode 中,是否可以排除 Apple Silicon 的源代码文件但将其包含在 Intel 中?
- python - 在 altair 图中为一些 x 标签着色?