Search code examples
angulartypescriptangular-servicesangular-componentsangular-event-emitter

Communication from Angular module to app component


In my Angular client I have one module call library. It does CRUD transactions related to books. I have an alert component and service in app root. That alert component is nested as a view child in app-component. Therefore once I perform CRUD actions, I want to inform the service in root from my library module.

What is the easiest way to build that communication?

AlertService

import { Injectable } from '@angular/core';

//Alert service 

@Injectable({
  providedIn: 'root'
})
export class AlertService {
  //Attributes
  show: boolean = false;
  type: string = 'info';
  message: string; 
  timeoutTimer: any; 

  //Constructor of the AlertService. 
  constructor() { }
  
  //Responsible for displaying the alert. 
  displayAlert(message: string, type: string = 'info', autohide: number = 5000) {
      this.show = true;
      this.message = message;
      this.type = type;
      
      //If timer is already available
      if (this.timeoutTimer) { 
          clearTimeout(this.timeoutTimer);
      }
      
      //If autohide is there then start the timeout 
      if (autohide) {
          setTimeout(() => {this.close()}, autohide);
      }
  }
  
  //Responsible for setting the show attribute false. 
  close() {
      this.show = false;
  }
  
}

Solution

  • I'm going to select an example from the Angular documentation to explain this.

    export class HeroListComponent implements OnInit {
      heroes: Hero[] = [];
      selectedHero: Hero | undefined;
    
      constructor(private service: HeroService) { }
    
      ngOnInit() {
        this.heroes = this.service.getHeroes();
      }
    
      selectHero(hero: Hero) { this.selectedHero = hero; }
    }
    

    The constructor(private service: HeroService) is where you injected the service into the component. You can now access all methods of HeroService inside of your component. So, you would want to make a method in your service, something like alert(message) { doSomething }, and then you call service.alert("Hello") in the component, usually during a method that is doing a CRUD operation. See how the ngOnInit() function is using the service and one of its methods to update data in the component.