Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a small service that retrieves notifications from a web socket. In the fillThemSomehow() method it retrieves and stores them to the array.

@Injectable()
export class WebsocketNotificationHandler {
    notifications: Array<Notification>;

    constructor() {
        this.notifications = [];
    }

    fillThemSomehow(): void {}
}

A component uses this service to retrieve and display the notifications:

@Component({ // selector, template, styles, pipes included })
export class NotificationsComponent {
    notificationsFilter: string = '';

    constructor(private _wsNotiHandler: WebsocketNotificationHandler) {}

    getLastNotifications(): Array<Notification> {
        return this._wsNotiHandler.notifications;
    }
}

...and the components 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>

So far so good, this works pretty well. As soon as the WebsocketNotificationHandler adds new notifications to the array, they are visible in the component view. This is just great.

But if I now want to filter the notifications in the view with a custom pipe, modifications in the array of the service are not published to the UI directly (only on keystroke of the input because the notificationsFilter model is changed). Template code of the ngFor looks like that now:

<div class="well notification" *ngFor="let notification of getLastNotifications() | search:notificationsFilter">

The SearchPipe is tested and does its job. My only issue is that this solution does not react on change in WebsocketNotificationHandler.notifications. What can I do to make it reactive?

I'm using TypeScript and Angular2 RC.1.

share|improve this question
up vote 2 down vote accepted

Angular doesn't check the contents of objects when change detection runs only if the object itself is a different one. You can set pure: false

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

to get the pipe executed even when it is still the same array instance.

See also https://angular.io/docs/ts/latest/guide/pipes.html

share|improve this answer
    
Works! Thanks for the quick solution. Forgot this tiny detail from the tutorial again... – jverhoelen May 13 '16 at 13:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.