angular service 进行组件通信

本文介绍如何在Angular应用中通过MessageService利用RxJS的Subject进行组件间的消息传递。MessageService作为服务提供者,使用Subject发布消息,发送消息的组件通过调用messageAction方法传递参数,接收消息的组件则通过订阅message$来获取消息。
MessageService 代码如下
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class MessageService {
  private messageSource = new Subject<string>();
  message$ = this.messageSource.asObservable();
  messageAction(name: string) {
    this.messageSource.next(name);
  }
}
发送消息的组件 代码如下

ts

import { Component} from '@angular/core';
import { MessageService } from '../service/message.service';
@Component({
  selector: 'app-send',
  templateUrl: './send.component.html',
  styleUrls: ['./send.component.css']
})
export class SendComponent {
  constructor(private messageService: MessageService) { }
  sendMessage(action: string) {
    this.messageService.messageAction(action);
  }

html

<input #action>
<button (click)="sendMessage(action.value)">action</button>
接收消息的组件

ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  action: string;
  sub: Subscription;
  ngOnInit(): void {
    this.messageService.message$.subscribe(action => this.action = action);
  }
  ngOnDestroy(): void {
    this.sub.unsubscribe(); //不要忘记取消订阅
  }
  constructor(private messageService: MessageService) {
  }

转载于:https://www.cnblogs.com/Godfunc/p/9848713.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值