private bookSubject = new Subject<string>();
// book$ 是 接收者 給需要的人取用拿資料回去
book$ = this.bookSubject.asObservable() as Observable<string>;
constructor() { }
setBook(name: string) {
this.bookSubject.next(name);
}
<h1>有接有資料</h1>
<p>{{bookName}}</p>
<button type="button" (click)="setBook('深入淺出C#')">
data 資料變成 深入淺出C#
</button>
bookName: string;
// unSubscription 用於 取消訂閱
private unSubscription = new Subject();
constructor(
private dataStoreService: DataStoreService) {
}
ngOnInit(): void {
this.dataStoreService.book$.pipe(
takeUntil(this.unSubscription)
).subscribe(name => {
this.bookName = name;
});
}
// 多添加的生命週期事件
ngOnDestroy(): void {
this.unSubscription.next();
this.unSubscription.complete();
}
setBook(name: string): void {
this.dataStoreService.setBook(name);
}