iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 17
0
Modern Web

Angular10 實作教學系列 第 17

NG10鐵人賽 - 17 - 資料傳遞處理 - 我丟要的接

利用 subject 放置 資料,讓 接收者 取得資料

data-store.service.ts

private bookSubject = new Subject<string>();

// book$ 是 接收者 給需要的人取用拿資料回去
book$ = this.bookSubject.asObservable() as Observable<string>;

constructor() { }

setBook(name: string) {
    this.bookSubject.next(name);
}

book.component.html

<h1>有接有資料</h1>
<p>{{bookName}}</p>
<button type="button" (click)="setBook('深入淺出C#')">
    data 資料變成 深入淺出C#
</button>

book.component.ts

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);
}

上一篇
NG10鐵人賽 - 16 - 資料傳遞處理 - 資料都給我
下一篇
NG10鐵人賽 - 18 - 資料傳遞處理 - 處理完再給你
系列文
Angular10 實作教學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言