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

组件间通信

如果是没有关系的组件之间通信(比如兄弟组件),我们可以建一个公用的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.csdn.net/weixin_39150852/article/details/102665986
https://www.jianshu.com/p/b4dcf96fbdd2

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值