用处
发布订阅者模式可以不用考虑组件之间的调用关系,用于父子,兄弟等组件传参。
创建一个message.service.ts文件
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ShareMsgService {
constructor() { }
private msg = new Subject<any>();
sendMessage(message: any) {
this.msg.next(message);
}
clearMessage() {
this.msg.next();
}
getMessage(): Observable<any> {
return this.msg.asObservable();
}
}
发送消息
import { ShareMsgService } from '../../message.service';
constructor(
private ShareMsgService: ShareMsgService,
) { }
this.ShareMsgService.sendMessage('想发送的消息')
接收消息
import { ShareMsgService } from '../../message.service';
import { Subscription } from "rxjs";
constructor(
private ShareMsgService: ShareMsgService,
) { }
subscription: Subscription
ngOnInit() {
this.subscription = this.ShareMsgService.getMessage().subscribe(data => {
this.accSettingFilter = data
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}