简体   繁体   English

非父子组件之间的通信

[英]Communication between non-parent-child components

I just want to do some experiment. 我只想做一些实验。 So when I click a button of a A component, some function of a B component should invoke. 因此,当我单击A组件的按钮时,应调用B组件的某些功能。 But I don't know how to do that if these components are not parent child to each other. 但是,如果这些组件不是彼此的父子组件,我不知道该怎么做。 Can you please help me 你能帮我么

When there is no child-parent relationship between components 组件之间没有子代关系时

You should create a service having a Subject and inject this service in both of these components. 您应该创建一个具有Subject的服务,并将该服务注入这两个组件中。

some.service.ts some.service.ts

@Injectable()
export class SomeService {
   public testSubject = new Subject<string>();
}

comp-a.component.ts COMP-a.component.ts

export class CompAComponent {
    constructor(private someService: SomeService) {
    }

    btnClickHandler() {
       this.someService.testSubject.next('clicked');
    }
}

comp-b.component.ts COMP-b.component.ts

export class CompBComponent {

    constructor(private someService: SomeService) {
       this.someService.testSubject.subscribe(next => { this.someFunction(data);});
    }

    someFunction(msg) {
       console.log(msg);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在非父子组件之间共享数据 - How to share data between non-Parent-child components Angular父子组件通信 - Angular communication between parent and child components 两个子组件之间的通信 - communication between two child components 在Angular 2中传递非父/子关系组件之间的值 - Passing Values Between Non-Parent/Child Relationship Components in Angular 2 Angular2在非父子组件之间传递数据 - Angular2 passing data between NON parent - child components Angular2:父子组件通信 - Angular2: Parent and Child Components Communication 有没有一种方法可以在不使用angualr中使用事件发射器的情况下在不是父级和子级的两个组件之间进行通信? - Is there a method to do communication between two components which are not parent and child without using event emitter in angualr? 使用@Input组件的父子之间的角向通信不起作用,但没有错误 - Angular communication between parent and child using @Input components doesn't work but gives no errors 在angular2中父母和子孙组件之间的数据通信(由路由器插座分开)? - Data communication between parent and grand-child components (separated by a router outlet) in angular2? 非相关组件之间使用 EventEmitter 进行通信 - Communication between non related components with EventEmitter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM