我有两个组件A和B,其中组件A包含一个按钮.我希望当用户点击此按钮时,在组件B上触发一个功能
<A></A> <router-outlet></router-outlet>
并且组件B使用routing进行渲染.我正在考虑使用具有可观察布尔值的服务,该服务指示是否单击了A中的按钮.这是实现它的正确方法吗?
解决方法
共享服务是非相关组件之间通信的常用方式.
您的组件需要 use a single instance of the service,因此请确保它在根级别提供.
您的组件需要 use a single instance of the service,因此请确保它在根级别提供.
使用BehaviorSubject as a data delegate的示例:
共享服务:
@Injectable() export class SharedService { isVisibleSource: BehaviorSubject<boolean> = new BehaviorSubject(false); constructor() { } }
第1部分:
export class Component1 { isVisible: boolean = false; constructor(private sharedService: SharedService) { } onClick(): void { this.isVisible = !this.isVisible; this.sharedService.isVisibleSource.next(this.isVisible); } }
第2部分:
export class Component2 { constructor(private sharedService: SharedService) { } ngOnInit() { this.sharedService.isVisibleSource.subscribe((isVisible: boolean) => { console.log('isVisible: ',isVisible); // => true/false }); } }
值得一提的是订阅时的BehaviorSubject会返回它所持有的最后一个值,因此上述示例中的组件将在实例化后立即使用最新值进行更新.
BehaviorSubject还允许在不订阅它的情况下获取其最新值:
this.sharedService.isVisibleSource.getValue(); // => true/false