【问题标题】:Communication from Angular module to app component从 Angular 模块到应用程序组件的通信
【发布时间】:2021-08-18 17:49:07
【问题描述】:

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

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

警报服务

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

【问题讨论】:

    标签: angular typescript angular-services angular-components angular-event-emitter


    【解决方案1】:

    我将从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() 函数如何使用服务及其方法之一来更新组件中的数据。

    【讨论】:

    • 我了解您的解决方案,但这不是我的问题。如果我误解了你的想法,我很抱歉,我的问题是我在模块内。在那里我无法导入位于根目录中的我的服务。如果有办法将警报服务从根目录导入到模块,那将是一个解决方案。
    • 您可能需要考虑将应用程序逻辑从模块中移出并移至服务或组件中。 NgModules 通常定义一组其他事物(组件、服务、类)。服务被导入到组件中,这就是它们实际“工作”的地方。服务在模块内部不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2019-11-12
    • 2017-01-23
    • 1970-01-01
    • 2014-10-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多