Angular 7单例服务在两个组件之间进行通信
创始人
2024-10-17 00:01:02
0

Angular 7中,可以使用单例服务在两个组件之间进行通信。下面是一个示例解决方法:

  1. 创建一个单例服务,例如CommunicationService,并在app.module.ts文件中将其提供为全局的单例服务。
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommunicationService {
  private messageSource = new Subject();
  message$ = this.messageSource.asObservable();

  sendMessage(message: string) {
    this.messageSource.next(message);
  }
}
  1. 在发送消息的组件中,将CommunicationService注入并调用sendMessage方法发送消息。
import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';

@Component({
  selector: 'app-sender',
  template: `
    
  `
})
export class SenderComponent {
  constructor(private communicationService: CommunicationService) {}

  sendMessage() {
    this.communicationService.sendMessage('Hello from SenderComponent!');
  }
}
  1. 在接收消息的组件中,将CommunicationService注入并订阅message$监听消息。
import { Component, OnDestroy } from '@angular/core';
import { CommunicationService } from './communication.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-receiver',
  template: `
    

{{ message }}

` }) export class ReceiverComponent implements OnDestroy { message: string; subscription: Subscription; constructor(private communicationService: CommunicationService) { this.subscription = this.communicationService.message$.subscribe(message => { this.message = message; }); } ngOnDestroy() { this.subscription.unsubscribe(); } }
  1. 在父组件中,将SenderComponentReceiverComponent添加到模板中。


这样,当点击“发送消息”按钮时,SenderComponent会调用CommunicationServicesendMessage方法发送消息,然后ReceiverComponent会监听到该消息并将其展示在页面上。

相关内容

热门资讯

盘点几款!hhpoker德州牛... 盘点几款!hhpoker德州牛仔视频,hhpoker是正规的吗,力荐教程(有挂透明);实战中需综合运...
热点推荐!hhpoker德州真... 这是一款非常优秀的hhpoker德州真的假的 ia辅助检测软件,能够让你了解到hhpoker德州真的...
传递经验!wepoker辅助是... 传递经验!wepoker辅助是真的吗,wpk模拟器多开,力荐教程(有挂方法)1、玩家可以在wepok...
盘点一款!wepokerplu... 此外,数据分析德州(wepokerplus透视脚本免费)辅助神器app还具备辅助透视行为开挂功能,通...
最新通报!wejoker内置辅... 最新通报!wejoker内置辅助,红龙poker辅助,大神讲解(有挂软件)是由北京得wejoker内...
一分钟了解!wepoker私人... 一分钟了解!wepoker私人局外卦,wepoker安装教程,AI教程(有挂方法)这是由厦门游乐互动...
2分钟细说!佛手大菠萝有挂吗,... 2分钟细说!佛手大菠萝有挂吗,德普之星有辅助软件吗,安装教程(有挂透视)准备好在德普之星有辅助软件吗...
大家学习交流!wepoker有... 大家学习交流!wepoker有脚本吗,wepoker插件下载,2025新版教程(有挂辅助)准备好在w...
新手必备!werplan透视挂... 新手必备!werplan透视挂,wepoker透视是真的吗,wpk教程(有挂辅助);最新版2024是...
解密关于!hhpoker是真的... 解密关于!hhpoker是真的还是假的,wepoker的辅助器,实用技巧(有挂软件);hhpoker...