- 01 借助Service单例进行通信 (试用场景:浏览器统一标签页)
- 02 借助localStorage进行通信 (试用场景:浏览器跨标签页通信)
01 借助Service单例进行通信 (试用场景:浏览器统一标签页)
注:在根模块的providers里注册一个service作为全局单例,利用这个单例的service在不同的组件之间进行通信。
// 1.1 用来充当'事件总线'的Service
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/Rx';
@Injectable()
export class EventService {
public event: BehaviorSubject<string> = new BehaviorSubject<string>('原来的我');
constructor() { }
}
// 1.2.1 ChildOneComponent
import { Component, OnInit } from '@angular/core';
import { EventService } from '../service/event.service';
@Component({
selector: 'app-child-1',
templateUrl: './child-1.component.html',
styleUrls: ['./child-1.component.css']
})
export class ChildOneComponent implements OnInit {
constructor(
public eventService: EventService
) { }
ngOnInit() {
}
public changeEvent(){
this.eventService.event.next('我不是原来的我了');
}
}
// 1.2.2 ChildTwoComponent
import { Component, OnInit } from '@angular/core';
import { EventService } from '../service/event.service';
@Component({
selector: 'app-child-2',
templateUrl: './child-2.component.html',
styleUrls: ['./child-2.component.css']
})
export class ChildTwoComponent implements OnInit {
event;
constructor(
public eventService: EventService
) { }
ngOnInit() {
this.eventService.event.subscribe((value) => {
this.event = value;
console.log(this.event); // '我不是原来的我了'
});
}
}
02 借助localStorage进行通信 (试用场景:浏览器跨标签页通信)
localStorage 被增/删/改的时候,都会触发一个事件,这就意味着不论在哪个标签页里修改了 localStorage,所有其它的标签页都能通过 window 对象监听到这个事件。因此,只要为localStorage赋值,便可跨标签页通信。
注:页面必须来自同一个域名,使用同一种协议,在同一个端口上。
// 2.1 ChildOneComponent
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child-1',
templateUrl: './child-1.component.html',
styleUrls: ['./child-1.component.css']
})
export class ChildOneComponent implements OnInit {
constructor() {}
ngOnInit() {
localStorage.setItem('event' , '原来的我');
}
changeEvent() {
localStorage.setItem('event' , '组件2,我变了');
}
}
// 2.2 ChildTwoComponent
import { Component, OnInit } from '@angular/core';
declare var window: any;
@Component({
selector: 'app-child-2',
templateUrl: './child-2.component.html',
styleUrls: ['./child-2.component.css']
})
export class ChildTwoComponent implements OnInit {
event;
constructor() {}
ngOnInit() {
/**
e.key localStroage 中被影响的键
e.newValue 为这个键所赋的新值
e.oldValue 这个键修改前的值
e.url 当前发生改变的页面 URL
**/
const that = this;
window.addEventListener('storage', function (e) {
if (e.key === 'event' ) {
that.event = e.newValue;
alert(that.event); // '组件2,我变了'
}
});
}
}
03 “歪后端嘛,来个websocket” (试用场景:山穷水尽【雾)
不过websocket作为一个没琢磨过的版块,留给日后搞清楚再哔哔了,挥。