作者:wjw0000 | 来源:互联网 | 2023-02-01 10:19
我在angular 4项目中有警报服务。所有组件都可以在该服务中设置警报,但是只有一些组件可以显示警报,而每个组件都可以在唯一的位置显示警报。所以我的问题是,如何在所有html文件中定义从服务获取变量?
我的服务如下所示:
import { Injectable } from '@angular/core';
@Injectable()
export class AlertService {
message;
constructor() { }
setMessage(message){
this.message = message;
}
}
要设置消息的组件只需导入服务并调用setMessage方法。但是当我尝试在html文件中使用消息时,例如:
{{message}}
然后超出范围。如何使该消息在所有组件的所有html文件中均可访问?
也许有比服务变量更好的方法来解决这种需求?
1> Joel Richman..:
为了在组件中使用消息,您需要在构造函数中注入服务(您可能正在这样做)。
零件:
export class MyComponent {
constructor(public alertService: AlertService)
在标记中,请参考alertService.message而不是message。
{{ alertService.message }}