在Angular中通过Subject进行组件之间通讯

Subject既可以当sender也可以自我subscribe,并且可以被多个订阅者订阅。

Angular中,我们可以通过创建一个服务来为不同的组件之间提供通讯服务。而通讯的实现就是通过Subject。

第一步:创建服务

import { Injectable,OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
 
@Injectable()
export class MessageService{
 
  sender = new Subject<string>();
  constructor() { }
}

服务很简单,一个sender成员变量,用于发送消息:this.sender.next('消息');同时它也可以订阅:this.sender.subscribe(next:()=>{});

注意使用该服务进行通讯一定要为同一个MessageService,否则它们得到的是不同的sender。这一点需要注意。

第二步:发送消息

this.msgService.sender.next(msg);

第三步:接收消息

this.msgSubscription = this.msgService.sender.subscribe(
    msg => {
        this.message = msg;
    }
)

第四步:消息接收方需要在destroy生命周期函数中取消订阅

  ngOnDestroy(){
    this.msgSubscription.unsubscribe();
  }

猜你喜欢

转载自blog.csdn.net/qq_38679823/article/details/129400853