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

标签 typescript angular

我有一个小型服务,可以从网络套接字检索通知。在 fillThemSomehow() 方法中,它检索它们并将其存储到数组中。

@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 将新通知添加到数组中,它们就会在组件 View 中可见。这太棒了。

但是,如果我现在想使用自定义管道过滤 View 中的通知,则服务数组中的修改不会直接发布到 UI(仅在输入按键时发布,因为 notificationsFilter 型号已更改)。 ngFor 的模板代码现在看起来像这样:

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

SearchPipe 经过测试并完成其工作。我唯一的问题是此解决方案不会对 WebsocketNotificationHandler.notifications 中的更改使用react。我该怎么做才能使其具有反应性?

我正在使用 TypeScript 和 Angular2 RC.1。

最佳答案

仅当对象本身是不同的对象时,当更改检测运行时,Angular 不会检查对象的内容。您可以设置pure: false

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

即使管道仍然是同一个数组实例,也能执行管道。

另请参阅https://angular.io/docs/ts/latest/guide/pipes.html

关于typescript - 将函数结果绑定(bind)到 Angular2 组件 (TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37210830/

相关文章:

angular - 检查 Angular2 中的权限

Angular 2 在 ngOnInit promise 中推送数组后不刷新 View

javascript - 当使用 rxjs 6 以 Angular 6 发出新请求时如何取消正在进行的 HTTP 请求

javascript - 如何在更改事件完成之前更新 DOM?

angular2 教程,const 变量的风格指南

angular - 如何在 Angular 中从可观察到 promise 转换

reactjs - 如何向React Table InminatedCheckbox方法添加类型

javascript - 替代 JSON.parse() 以保持小数精度?

javascript - 为什么ngRX操作具有类型?

python - 如何使用selenium调用angular函数(ng-click)