简体   繁体   English

将函数结果绑定到 Angular2 组件(TypeScript)

[英]Binding function result to Angular2 component (TypeScript)

I have a small service that retrieves notifications from a web socket.我有一个从 Web 套接字检索通知的小型服务。 In the fillThemSomehow() method it retrieves and stores them to the array.fillThemSomehow()方法中,它检索并将它们存储到数组中。

@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: ...和组件 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.一旦 WebsocketNotificationHandler 向数组添加新通知,它们就会在组件视图中可见。 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).但是,如果我现在想使用自定义管道过滤视图中的通知,则不会直接将服务数组中的修改发布到 UI(仅在输入的按键时,因为notificationsFilter模型已更改)。 Template code of the ngFor looks like that now: ngFor 的模板代码现在看起来像这样:

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

The SearchPipe is tested and does its job. SearchPipe 已经过测试并完成其工作。 My only issue is that this solution does not react on change in WebsocketNotificationHandler.notifications .我唯一的问题是此解决方案不会对WebsocketNotificationHandler.notifications更改做出反应。 What can I do to make it reactive?我该怎么做才能使它具有反应性?

I'm using TypeScript and Angular2 RC.1.我正在使用 TypeScript 和 Angular2 RC.1。

Angular doesn't check the contents of objects when change detection runs only if the object itself is a different one.仅当对象本身是不同的对象时,Angular 才会在运行更改检测时检查对象的内容。 You can set pure: false您可以设置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另见https://angular.io/docs/ts/latest/guide/pipes.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM