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