【发布时间】:2016-03-20 08:34:08
【问题描述】:
我有一个 Angular 2 组件,它显示项目列表,并注册到发布事件的服务。问题是,即使我在收到事件时什么都不做,Angular 也会更新视图(或者至少在我猜不应该做的时候做一些事情)。
正如您在控制台中看到的,每次我的服务发布消息时都会调用我的项目的“getTitle()”方法。
即使我没有注册到我的服务并且我的组件没有实现 MyServiceListener 接口,每次服务收到消息时都会调用 getTitle。如果我不在它的构造函数中为我的组件提供服务,那么一切都很好。所以,我的依赖注入似乎有问题,但是什么?
这里是plunker的相关代码:
我的服务及其监听器接口:
export interface MyServiceListener {
onMessage(_message: any);
}
export class MyService {
private m_listener: MyServiceListener;
constructor() {
window.setInterval(() => {
if (this.m_listener !== undefined) {
this.m_listener.onMessage("Hi");
}
}, 500);
}
setListener(_listener: MyServiceListener) { this.m_listener = _listener; }
}
物品类:
export class Item {
m_title: string;
constructor(_title: string) {
this.m_title = _title;
}
getTitle(): string { console.log("getTitle"); return this.m_title; }
}
我的组件:
@Component({
selector: 'my-app',
template : `
<div>
<ul>
<li *ng-for="#item of m_items">
{{item.getTitle()}}
</li>
</ul>
</div>
`
})
export class App implements TestBugAngularServiceListener {
private m_items: Array<Item> = new Array<Item>();
constructor(_communicationService: MyService) {
this.m_items.push(new Item("A"));
this.m_items.push(new Item("B"));
this.m_items.push(new Item("C"));
_communicationService.setListener(this);
}
onMessage(_message: any) {
}
}
bootstrap(App, [MyService]).catch(err => console.error(err));
【问题讨论】:
标签: angularjs service dependency-injection components