Angular 4事件发射器未捕获订阅上的任何内容
一个月前,我发布了一个小程序,它只允许显示正在加载的动画 为此,我的用户只需将Angular 4事件发射器未捕获订阅上的任何内容,angular,eventemitter,Angular,Eventemitter,一个月前,我发布了一个小程序,它只允许显示正在加载的动画 为此,我的用户只需将添加到他们的模板中,并将LoadService插入他们的组件中,然后调用LoadService.animate(true)(或false) 在图书馆方面,我做了以下工作: 为我服务: @Injectable() export class LoadService { // My event emitter @Output() animating: EventEmitter<any> = new Eve
添加到他们的模板中,并将LoadService
插入他们的组件中,然后调用LoadService.animate(true)
(或false)
在图书馆方面,我做了以下工作:
为我服务:
@Injectable()
export class LoadService {
// My event emitter
@Output() animating: EventEmitter<any> = new EventEmitter();
constructor() {}
// Method called by the user to display the animation,
// emits the value passed as parameter
public animate(val: boolean) {
this.animating.emit(val);
}
getValue(): any {
return this.animating;
}
}
我的HTML
模板只有一个
来显示或隐藏CSS
动画
因此,我的事件发射器会发射我的用户提供给animate
的内容,布尔值在我的组件中应该会发生变化,或者一个月前就发生了变化
由于某些原因,我的事件发射器上的订阅没有捕获任何内容
eventemitter
是否已更改?我是否以错误的方式使用了它们?由于您使用的是原始数据类型布尔值
,因此可能存在对象引用保持不变的情况,因此它不会触发订阅
- 所以使用一个复杂的对象
let animation ={ allowAnimation : true/false }; this.animating.emit(animation); // might trigger the subscription
- 递增计数器(数字)
注意:如果第一种情况未触发,则您可以更改引用并发出,这将导致订阅触发。您的代码存在多个问题。首先,@Output在组件中使用,而不是在服务中使用。其次,您订阅的是getValue(),它不返回可观察的,订阅无法工作。第三,如果您希望您的服务将数据推送到订阅者,请使用Rx.Subject,因为EventEmitter只是主题之上的另一层抽象,其行为在将来可能会发生变化 这就是我所想的,在阅读了有关EventEmitter的详细信息后,我现在意识到我的实现如何在将来(或者就目前而言)导致问题。对我来说,什么是最好的方法?要创建组件将订阅的
Observable
,请在getValue()中尝试返回Observable.of(this.animating)并从代码中删除@Output。因为emit何时执行更改检测??
let animation ={
allowAnimation : true/false
};
this.animating.emit(animation); // might trigger the subscription
this.animating.emit(i++);