Search code examples
angulareventemitter

EventEmmiter send data to no sibling component - Angular 2


I had one component that consisted of button that triggers function and table that generate elements according to data that i got from service and that function.

But I had to split that component, and now i have only button on one component, and function and table with data on other component.

In first component with button I set EventEmmiter like this:

import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { ConceptService } from "app/services/rest/concept.service";

@Component( {
    selector: 'co-calculation',
    templateUrl: './co-calculation.component.html',
    styles: []
} )

export class CoCalculationComponent implements OnInit {

    dataSent: EventEmitter<any> = new EventEmitter();

    constructor( private conceptService: ConceptService ) { }

    ngOnInit() {}

    calculate(){
      this.conceptService.calculateCoDatabase().subscribe( (response:any) => {

            this.dataSent.emit(response);

           }); } }

On other component I have function that I want to triger when I click on button and instead want to set emit to replace service subscription on start of function.

2nd component:

import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';

import { ConceptService } from "app/services/rest/concept.service";
import { CoCalculationComponent } from "app/components/02_top/scm/co-calculation/co-calculation.component";

@Component( {
    selector: 'co-database-table',
    templateUrl: './co-database-table.component.html',
    styles: []
} )
export class CoDatabaseTableComponent implements OnInit {

    data;

    constructor( private conceptService: ConceptService ) {  }

    ngOnInit() {
    }

    generateTable(){

        this.conceptService.calculateCoDatabase().subscribe( (response:any) => {

            this.data = response;
            console.log('data'); 
//rest of function is irrelevant//
} 

I don't know how to trigger function in second component and pass emit from first component instead of service subscribe. Thanks


Solution

  • Now, this will depend upon what is the relation between the two components now. We can use event Emitters if we have a parent child relationship and you want to call a method on parent when the button is clicked in child, show us the relationship, and we can explain how to do it.

    If they are not related at all, for then you can use a service and create a Subject there, which can both be ab observer and an Observable.

    Have a service like:

    @Injectable()
    export class ActionService {
    
      private actionSource = new Subject<boolean>();
      actionSourceObservable = this.actionSource.asObservable();
    
      constructor() { }
    
      buttonClicked() {
        this.actionSource.next(true)
      }
    
    }
    

    Now, inject the service in both the components, In the first component when you click the button call a function like:

    foo() {
        // do your job here and then:
        this.actionService.buttonCliked();
    }
    

    In the other component, have something like this in your ngOnInit()

    this.actionService.actionSourceObservable.subscribe(() => {
        // call the function in the second component, for example
        secondCompFunc();
    })