某些事件未触发更改检测

时间:2016-12-19 17:55:21

标签: angular angular2-changedetection

我有一个subscribes来自Observable service的组件。当observable发出next值时,我的组件会发生一些变化。奇怪的是,组件将根据next值的生成方式更新或不更新视图。如果我理解正确的话,一些事件已经被角度2修补,以触发变化检测,而有些则没有。 MIDI事件是其中一个没有(这使得有点敏感)。

如果服务查找单击事件以触发下一个值,则更改将反映在视图中。因此发生了变化检测。

如果服务查找键盘事件同样的事情,则会发生更改检测。

但是,当服务使用MIDI事件时,不会发生更改检测。

这里有一些代码:

export class App {

  arr = [
      {id: 1, status: false},
      {id: 2, status: false},
      {id: 3, status: false}
    ];

  thing = new Subject<boolean>();

  constructor(private renderer: Renderer,
              private ser:Ser,
              private midi: MidiService) {}

  ngOnInit(){
    // listening to click events, will trigger change detection
    this.renderer.listenGlobal('document', 'click', (event) => {
      console.log("Left click", event);
      this.thing.next(1);
    });
    this.thing.subscribe( v => this.toggle(v));
    // my midi service events will call the toggle method however the 
    // changes won't be displayed in the view
    this.midi.notesPayed$.subscribe(v => this.toggle(v));
  }

这是一个plnkr:

https://plnkr.co/edit/SS6jwgQg4TVdOCC05cNV?p=preview

我不确定这是否是来自角度2的基础工作的错误或特征。无论如何我想知道为什么这种情况发生。通过自己调用更改检测可以轻松解决具体问题,因此我不需要解决方案。

1 个答案:

答案 0 :(得分:5)

这已知的行为。 zone.js不包含MIDI API,因此Angulare无法获得运行更改检测的通知。

注入zone:NgZone并使用this.zone.run(() => {...})

包装更改模型的代码

或注入cdRef:ChangeDetectorRef并通过调用this.cdRef.detectChanges()

在更改后调用更改检测