我有一个小型服务,可以从网络套接字检索通知。在 fillThemSomehow()
方法中,它检索它们并将其存储到数组中。
@Injectable()
export class WebsocketNotificationHandler {
notifications: Array<Notification>;
constructor() {
this.notifications = [];
}
fillThemSomehow(): void {}
}
组件使用此服务来检索和显示通知:
@Component({ // selector, template, styles, pipes included })
export class NotificationsComponent {
notificationsFilter: string = '';
constructor(private _wsNotiHandler: WebsocketNotificationHandler) {}
getLastNotifications(): Array<Notification> {
return this._wsNotiHandler.notifications;
}
}
...以及组件 HTML:
<input class="form-control" [(ngModel)]="notificationsFilter">
<div class="well notification" *ngFor="let notification of getLastNotifications()">
<span [innerHtml]="notification.getHtml()"></span>
<small class="pull-right">{{notification.time | dateTime}}</small>
</div>
到目前为止一切顺利,效果非常好。一旦 WebsocketNotificationHandler 将新通知添加到数组中,它们就会在组件 View 中可见。这太棒了。
但是,如果我现在想使用自定义管道过滤 View 中的通知,则服务数组中的修改不会直接发布到 UI(仅在输入按键时发布,因为 notificationsFilter
型号已更改)。 ngFor 的模板代码现在看起来像这样:
<div class="well notification" *ngFor="let notification of getLastNotifications() | search:notificationsFilter">
SearchPipe 经过测试并完成其工作。我唯一的问题是此解决方案不会对 WebsocketNotificationHandler.notifications 中的更改使用react。我该怎么做才能使其具有反应性?
我正在使用 TypeScript 和 Angular2 RC.1。
最佳答案
仅当对象本身是不同的对象时,当更改检测运行时,Angular 不会检查对象的内容。您可以设置pure: false
@Pipe({
name: 'flyingHeroes',
pure: false
})
即使管道仍然是同一个数组实例,也能执行管道。
关于typescript - 将函数结果绑定(bind)到 Angular2 组件 (TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37210830/