1. 程式人生 > >【angular5項目積累總結】消息訂閱服務

【angular5項目積累總結】消息訂閱服務

imp blog const service pri con this ams 列表

code

import { Injectable } from ‘@angular/core‘;
import { Subject } from ‘rxjs/Subject‘;
@Injectable()
export class CommonService {
    private notify = new Subject<any>();
    /**
     * Observable string streams
     */
    notifyObservable$ = this.notify.asObservable();

    constructor() { }

    public notifyOther(data: any) {
        
if (data) { this.notify.next(data); } } }

項目示例

表單提交後更新其他組件數據列表

定義:

  constructor(
        private router: Router,
        private actRouter: ActivatedRoute,
        private appStoreService: AppStoreService,
        private comService: CommonService) {
         this.subscribeUpdate(comService);
    }

 subscribeUpdate(comService: CommonService) {
        
this.comService.notifyObservable$.subscribe(data => { if (data == ‘refreshWebApp‘) { this.loadWebApp(); } }, error => { console.log(`subscribe error:${error}`) }) }

調用:

this.comService.notifyOther(‘refreshWebApp‘);

【angular5項目積累總結】消息訂閱服務