微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从 angular 模块到应用程序组件的通信

在我的 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 documentation 中选择一个示例来解释这一点。

constructor(private service: HeroService)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。