Augury显示更改检测默认事件,但配置了ChangeDetectionStrategy.OnPush

时间:2017-06-13 15:17:50

标签: angular angular2-changedetection

我有一个Angular(4)组件,我已经激活了ChangeDetectionStrategy.OnPush:

tile.component.ts

import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
import { Tile } from './tile';

@Component({
    selector: 'tile',
    template: `
        <div>
        <div>{{this.data.title}}</div>
        <div>{{this.data.image}}</div>
    </div>
    `,
    styleUrls: ['./tile.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TileComponent {

    @Input() data: Tile;

    constructor() {}
}

tile.ts

import { List, Map } from 'immutable';

export class Tile {
  _data: Map<string, any>;

  get title() {
      return <string> this._data.get('title');
  }

  setTitle(value: string) {
      return new Tile(this._data.set('title', value));
  }

  get image() {
      return <string> this._data.get('image');
  }

  setImage(value: string) {
      return new Tile(this._data.set('image', value));
  }

  constructor(data: any = undefined) {
    data = data || { title: '', image: '' };
    this._data = Map<string, any>(data);
  }
}

但是当我运行它时,Augury总是会将此组件显示为ChangeDetectionStrategy.Defaultenter image description here

不会抛出任何错误。

有人知道为什么ChangeDetectionStrategy会被恢复为Default,或者如果Augury可能显示错误的值,我如何测试是否确实会正确配置ChangeDetectionStrategy.OnPush?

非常感谢:)

1 个答案:

答案 0 :(得分:1)

以下是可用于检查当前ChangeDetectionStrategy的简单测试。添加以下代码:

@Input() data: Tile = {'title': 'title', 'image': 'image'} as Tile; 

constructor() { 
    setTimeout(()=>{ 
          this.data = {'title': 'hello', 'image': 'image'} as Tile; 
          console.log("/// timeout executed"); }, 5000); 
    }

如果您的观看次数在5秒内更新,那么您有ChangeDetectionStrategy.Default,如果没有,则为ChangeDetectionStrategy.OnPush

您提到该视图未更新,这意味着当前策略为OnPush Augury显示错误信息

要查看更改,您可以修改如下示例:

@Input() data: Tile = {'title': 'title', 'image': 'image'} as Tile; 

constructor(private cd: ChangeDetectorRef) { 
    setTimeout(()=>{ 
          this.data = {'title': 'hello', 'image': 'image'} as Tile; 
          console.log("/// timeout executed"); }, 5000); 
          this.cd.detectChanges();
    }