Angular 从角度模块到应用程序组件的通信
在我的angular客户端中,我有一个模块调用库。它进行与书籍相关的CRUD交易。我在应用程序根目录中有一个警报组件和服务。该警报组件嵌套为应用程序组件中的视图子组件。因此,一旦执行CRUD操作,我想从我的库模块通知root中的服务。有谁能帮我找出建立这种沟通的最简单方法吗。先谢谢你 警报服务Angular 从角度模块到应用程序组件的通信,angular,typescript,angular-services,angular-components,angular-event-emitter,Angular,Typescript,Angular Services,Angular Components,Angular Event Emitter,在我的angular客户端中,我有一个模块调用库。它进行与书籍相关的CRUD交易。我在应用程序根目录中有一个警报组件和服务。该警报组件嵌套为应用程序组件中的视图子组件。因此,一旦执行CRUD操作,我想从我的库模块通知root中的服务。有谁能帮我找出建立这种沟通的最简单方法吗。先谢谢你 警报服务 import { Injectable } from '@angular/core'; //Alert service @Injectable({ providedIn: 'root' }) e
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;
}
}
我将从中选择一个例子来解释这一点
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; }
}
构造函数(私有服务:HeroService)
是将服务注入组件的地方。您现在可以访问组件内部的所有服务方法。因此,您需要在服务中创建一个方法,类似于alert(message){doSomething}
,然后在组件中调用service.alert(“Hello”)
,通常是在执行CRUD操作的方法期间。查看ngOnInit()函数如何使用服务及其方法更新组件中的数据。我了解您的解决方案,但这不是我真正的问题。很抱歉,如果我误解了您的IDE,我的问题是我在模块内。在那里,我无法导入根目录中的“我的服务”。如果有一种方法可以将警报服务从根目录导入模块,那么这将是一个解决方案。您可能需要考虑将应用程序逻辑移出模块,并移入服务或组件。NgModules通常定义一组其他东西(组件、服务、类)。服务被导入到组件中,这就是它们实际“工作”的地方。服务在模块内部不工作。