从 Angular 模块到应用程序组件的通信

Communication from Angular module to app component

在我的 Angular 客户端中,我有一个模块调用库。它执行与书籍相关的 CRUD 事务。我在应用程序根目录中有一个警报组件和服务。该警报组件嵌套为应用程序组件中的视图子项。因此,一旦我执行了 CRUD 操作,我想从我的库模块通知根目录中的服务。

建立这种沟通最简单的方法是什么?

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;
  }
  
}

我将 select 来自 Angular documentation 的例子来解释这一点。

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; }
}

constructor(private service: HeroService) 是您将服务注入组件的地方。你现在可以在你的组件中访问 HeroService 的所有方法。因此,您可能希望在您的服务中创建一个方法,例如 alert(message) { doSomething },然后您在组件中调用 service.alert("Hello"),通常是在执行 CRUD 操作的方法期间。查看 ngOnInit() 函数如何使用服务及其方法之一来更新组件中的数据。