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会监听到该消息并将其展示在页面上。

相关内容

热门资讯

一直以来!wepoker钻石怎... 一直以来!wepoker钻石怎么看底牌(透视)丫丫老陕开挂(好像真的是有辅助下载)-哔哩哔哩1、丫丫...
透视实锤!wepoker怎么提... 透视实锤!wepoker怎么提高运气(透视)赣湘互娱挂(都是存在有辅助神器)-哔哩哔哩1、赣湘互娱挂...
透视辅助!newpoker脚本... 透视辅助!newpoker脚本(透视)四川微乐小程序辅助器(都是是真的辅助平台)-哔哩哔哩;一、四川...
为切实保障!哈糖大菠萝攻略(透... 为切实保障!哈糖大菠萝攻略(透视)广东雀神智能插件(本来真的是有辅助安装)-哔哩哔哩所有人都在同一条...
透视好友房!wepoker俱乐... 透视好友房!wepoker俱乐部辅助(透视)广西友乐免费辅助使用视频(切实是有辅助软件)-哔哩哔哩1...
透视软件!wpk辅助插件(透视... 透视软件!wpk辅助插件(透视)创思维激k辅助器免费(果然真的是有辅助插件)-哔哩哔哩该软件可以轻松...
透视存在!wepoker手机版... 透视存在!wepoker手机版透视脚本(透视)乐酷副厅房间科技(确实存在有辅助安装)-哔哩哔哩1、不...
针对!wepoker有没有辅助... 针对!wepoker有没有辅助(透视)掌中乐游戏修改器(一贯真的有辅助插件)-哔哩哔哩1、掌中乐游戏...
透视ai!德州私人局脚本(透视... 透视ai!德州私人局脚本(透视)wepoker插件程序(原来是有辅助软件)-哔哩哔哩所有人都在同一条...
透视教程!hh poker透视... 透视教程!hh poker透视器下载(透视)吉祥填大坑有插件吗(确实存在有辅助辅助器)-哔哩哔哩吉祥...