首页 > 解决方案 > 检测 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, },
    ]
};

标签: angular

解决方案


非常抽象,因为您没有提供太多细节。

将播放的声音提取到单独的组件中,提取Observable.interval到单独的服务中。

component1在您的and中使用您的声音播放组件component2(您可以通过 切换其可见性*nfIg)并使用您Observable.interval的声音播放组件。

声音播放组件可以接收参数,告诉它哪个父级正在使用它,因为和@Input() contextType的声音应该不同。component1component2

[根据您添加的上下文更新]

由于声音播放显然是两个组件的共同点,我将在单独的地方提取它,在使用和soundPlayingComponent的父级中使用它,并让这两个组件根据将播放的适当声音暴露给父级。ListComponentDetailsComponentOutput() playSound:EventEmitter<whateverParamsYouNeed>


推荐阅读