我有一個從Web套接字檢索通知的小服務。在fillThemSomehow()
方法中,它檢索並將它們存儲到數組中。將函數結果綁定到Angular2組件(TypeScript)
@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向數組添加新的通知,它們就可以在組件視圖中看到。這太好了。
但是,如果我現在想用自定義管道過濾視圖中的通知,則服務數組中的修改不會直接發佈到UI(僅在輸入的擊鍵上,因爲notificationsFilter
模型已更改)。 ngFor的模板代碼如下所示:
<div class="well notification" *ngFor="let notification of getLastNotifications() | search:notificationsFilter">
SearchPipe已經過測試並完成其工作。我唯一的問題是這個解決方案不會對WebsocketNotificationHandler.notifications
的變化做出反應。我能做些什麼來使其具有反應性?
我正在使用TypeScript和Angular2 RC.1。
工程!感謝您的快速解決方案。再次從教程中忘記了這個細節... – jverhoelen