在角度2中使用$ on和$ broadcast [英] using $on and $broadcast with angular 2
问题描述
当前使用angularjs 1,我正在使用$on
和$broadcast
事件机制,它们是$rootscope
和$scope
的一部分,可用于处理控制器和服务之间的通信.但是,随着AngularJS 2的引入,$rootscope
和$scope
将变得不可用.因此,如果我想使我的应用程序与AngularJS 2兼容,那么该怎么做才能获得与$on
和$broadcast
相同的效果.
Currently with angularjs 1, I am using the $on
and $broadcast
event mechanisms, which are available as part of $rootscope
and $scope
, to handle communication between a controller and a service. However, with the introduction of AngularJS 2, $rootscope
and $scope
will become unavailable. So, if I want to make my application AngularJS 2-compliant, then what should I do to get the same effect as $on
and $broadcast
.
推荐答案
您可以使用包含类型为Observable
的属性的共享服务.这是一个示例实现:
You could use a shared service containing a property of type Observable
. Here is a sample implementation:
export class SharedService {
observable: Observable;
observer: Observer;
constructor() {
this.observable = Observable.create((observer:Observer) => {
this.observer = observer;
}).share();
}
broadcast(event) {
this.observer.next(event);
}
on(eventName, callback) {
this.observable.filter((event) => {
return event.name === eventName;
}).subscribe(callback);
}
}
您会注意到您需要共享可观察的对象,因为默认情况下它是冷的.
You can notice that you need to share the observable because it's cold by default.
重要的是在于在引导应用程序时定义您的服务,以便能够在整个应用程序中使用相同的实例:
An important thing consists in defining your service when bootstrapping your application to be able to use the same instance within the whole application:
bootstrap(AppComponet, [ SharedService ]);
以下是相应的插件: https://plnkr.co/edit/bpIVxRrWggLVrS9BdQ6w?p=预览.
有关更多详细信息,请参见此问题:
See this question for more details:
这篇关于在角度2中使用$ on和$ broadcast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!