仅在OnInit之后如何启动iterableDiffer?

时间:2019-08-28 10:00:46

标签: javascript angular typescript

我的问题是,当我只初始化数据库中的数据时,iterableDiffer会检测到更改。我不想获得此第一个更改检测。我只想在用户编辑数组时获得更改检测。

我试图将数据库请求放入构造函数中。没有改变任何东西。


  constructor(
    private route: ActivatedRoute,
    private StoreService: StoreService,
    private iterableDiffers: IterableDiffers
  ) {
     this.iterableDiffer = 
       this.iterableDiffers.find([]).create(null);
  }

  myArray: MyClass[] = [];

  iterableDiffer: IterableDiffer<unknown>;

  ngOnInit() {
    const id = this.route.snapshot.params.id;
    this.StoreService.getData(id)
       .subscribe(data => this.myArray = data);
    // on this subscribe, the Differ falsely gets triggered
  }

  ngAfterViewChecked() {
    const changes = this.iterableDiffer.diff(this.myArray);
    if (changes) {
      changes.forEachAddedItem((record: IterableChangeRecord<MyClass>) => {

        console.log('Added Changes detected');

        this.StoreService.addToDatabase(record.item);
      });
    }
  }

  // gets called by User Click, here i want to have the Differ called
  // This works fine
  addElmt(elmt: MyClass) {
    this.myArray.push(elmt);
  }

代码段是实际代码的简化版本。我无法在函数StoreService.addToDatabase()中调用addElmt()。这只是为了更好的解释。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

总是可以有一个变量“ myObserver”并执行

myObserver:any=null
ngAfterViewChecked() {
    const changes = this.iterableDiffer.diff(this.myArray);
    if (changes) {
      changes.forEachAddedItem((record: IterableChangeRecord<MyClass>) => {

        console.log('Added Changes detected');

        this.StoreService.addToDatabase(record.item);
      });
    }
    if (!myObserver)
    {
      const id = this.route.snapshot.params.id;
      myObserver=this.StoreService.getData(id)
         .subscribe(data => this.myArray = data);
    }
}