2016-05-13 75 views
2

我有一個從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。

回答

2

僅當對象本身不同時,角度纔會在更改檢測運行時檢查對象的內容。您可以設置pure: false

@Pipe({ 
    name: 'flyingHeroes', 
    pure: false 
}) 

即使它仍然是相同的數組實例,以獲得流水線執行。

另請參見https://angular.io/docs/ts/latest/guide/pipes.html

+0

工程!感謝您的快速解決方案。再次從教程中忘記了這個細節... – jverhoelen