Angular 6中Service组件通信问题:子组件未进入判断逻辑
解决Angular 6中Service组件通信(hover子菜单未接收事件)的问题
我之前碰到过一模一样的场景,问题的核心其实出在子组件的初始化时机和你用的Subject的特性上:
你的子组件是hover菜单才会显示的,这意味着父组件触发notifyOther发送事件的时候,子组件大概率还没完成初始化、也没订阅那个Observable。而Subject的特性是不会保存已经发出的事件——当子组件后来才订阅时,早就错过了之前的事件,自然不会进入你写的判断逻辑里。
下面是具体的修复方案:
1. 把Subject换成BehaviorSubject
BehaviorSubject会自动保存最近一次发出的值,当新的订阅者出现时,会立刻把这个最近的值推送给它。修改你的Service代码:
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable() export class ComponentCommunicationService { // 给个初始值,比如null就行,后续会被覆盖 private notify = new BehaviorSubject<any>(null); notifyObservable$ = this.notify.asObservable(); constructor(){} public notifyOther(data: any) { if (data) { this.notify.next(data); } } }
2. 子组件里处理初始值
因为BehaviorSubject在订阅时会先发送我们设置的初始null值,所以子组件里要先跳过这个空值,避免无效判断:
ngOnInit() { this.componentCommunicationService.notifyObservable$.subscribe(res => { // 先跳过初始的null,只处理有效事件 if (!res) return; if (res.hasOwnProperty('option') && res.option === 'call from menu') { console.log(res.value) this.isRoldFound= res.value; } }) }
额外的优化提醒
- 如果你不想用BehaviorSubject,用
ReplaySubject(1)也可以,它和BehaviorSubject类似,但不需要设置初始值,只会保存最近的1次事件。 - 别忘了在子组件销毁时取消订阅,防止内存泄漏:
import { Subscription } from 'rxjs'; private notifySubscription: Subscription; ngOnInit() { this.notifySubscription = this.componentCommunicationService.notifyObservable$.subscribe(res => { // ... 你的逻辑代码 }) } ngOnDestroy() { if (this.notifySubscription) { this.notifySubscription.unsubscribe(); } }
这样调整之后,当你hover显示子组件时,它订阅Observable的瞬间就能收到父组件之前发出的事件,自然会进入你写的判断逻辑啦。
内容的提问来源于stack exchange,提问作者angularguy
相关产品推荐
相关产品推荐

