angular组件通信-通过service服务的方式

文章介绍了在Angular应用中,如何通过创建一个公共服务并结合Subject来实现没有直接关系的组件(如兄弟组件)之间的通信。具体做法是,在服务中定义一个Subject,发布组件触发事件时调用next方法,而处理逻辑的组件则进行订阅并响应变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

组件间通信

如果是没有关系的组件之间通信(比如兄弟组件),我们可以建一个公用的service,通过共享subject的方式实现通信。

service

import { Injectable } from '@angular/core';

import { Subject } from 'rxjs';
@Injectable({
  providedIn: 'root',
})
export class SearchPanelResetAllService {
  isResetAll$ = new Subject<string>();  //自定义变量名,触发函数时使用,用于订阅
  isResetAllChange$ = this.isResetAll$.asObservable();//自定义变量名,在组件中使用
  constructor() {}
}

A组件(发布组件,触发事件的那个)

import { Component, OnInit, OnDestroy} from '@angular/core';
import { SearchPanelResetAllService} from 'src/app/service/searchPanelResetAll.service';
@Component({
    selector: 'app-a',
    templateUrl: '.a.component.html',
    styleUrls: ['./a.component.scss']
})
export class AComponent implements OnInit, OnDestroy {
   
   
    constructor(public searchPanelResetAllService: SearchPanelResetAllService,) {

    }

  SearchPanelResetAll() {
    this.searchPanelResetAllService.isResetAll$.next('true');
  }
}

B组件(处理逻辑)

import { Component, OnInit, OnDestroy} from '@angular/core';
import { CommonshareService } from 'src/app/service/commonshare.service';
@Component({
    selector: 'app-b',
    templateUrl: '.a.component.html',
    styleUrls: ['./a.component.scss']
})
export class BComponent implements OnInit, OnDestroy {
   
    public exsceneSub: any;
    constructor(public searchPanelResetAllService: SearchPanelResetAllService,) {
        this.exsceneSub = this.searchPanelResetAllService.isResetAllChange$.subscribe(data => {
            if (data === 'true') {
                this.resetAll();
            }
        });
    }
    resetAll(){
        console.log('resetAll');
    }

    ngOnDestroy(): void {

        this.exsceneSub.unsubscribe(); //释放句柄
    }
}

https://blog.youkuaiyun.com/weixin_39150852/article/details/102665986
https://www.jianshu.com/p/b4dcf96fbdd2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值