安裝:
npm install --save eventemitter3
創建event.service
import { Injectable } from '@angular/core'; // var EventEmitter = require('eventemitter3'); import { EventEmitter } from 'eventemitter3'; @Injectable({ providedIn: 'root' }) export class EventService { public event:any; constructor() { this.event=new EventEmitter(); //這個實例就會被多個組件共享 來實現不同頁面的數據通信 } }
使用
比如登陸成功后,更新個人中心頁面數據:
登陸頁面,引入事件服務:
在登陸成功后發布事件:
//通知用戶中心更新用戶信息 this.eventService.event.emit('useraction');
個人中心監聽事件:
ngOnInit() { //監聽注冊 登錄成功的事件 this.eventService.event.on('useraction',()=>{ var userinfo=this.storage.get('userinfo'); if(userinfo && userinfo.username){ this.userinfo=userinfo; }else{ this.userinfo=''; } }) }