组件间通信
如果是没有关系的组件之间通信(比如兄弟组件),我们可以建一个公用的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