2

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Works! Thanks for the quick solution. Forgot this tiny detail from the tutorial again...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.