简体   繁体   中英

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. 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.

some.service.ts

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

comp-a.component.ts

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

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

comp-b.component.ts

export class CompBComponent {

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM