更新时间:2023-02-13 23:34:27
共享服务是非相关组件之间常见的通信方式.您的组件需要使用服务的单个实例,因此请确保它在根级别提供.
Shared service is a common way of communication between non-related components. Your components need to use a single instance of the service, so make sure it's provided at the root level.
共享服务:
@Injectable()
export class SharedService {
isVisibleSource: BehaviorSubject<boolean> = new BehaviorSubject(false);
constructor() { }
}
组件 1:
export class Component1 {
isVisible = 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(): void {
this.sharedService.isVisibleSource.subscribe((isVisible) => {
console.log('isVisible: ', isVisible); // => true/false
});
}
}
值得一提的是,BehaviorSubject
在订阅时返回它持有的最后一个值,因此上面示例中的组件将在实例化后立即更新为最新值.
It is worth mentioning that BehaviorSubject
upon a subscription returns the last value it holds, therefore the component from the example above will be updated with the most recent value immediately after the instantiation.
BehaviorSubject
还允许在不订阅的情况下获取其最新值:
BehaviorSubject
also allows to get its most recent value without even subscribing to it:
this.sharedService.isVisibleSource.getValue(); // => true/false