gpt4 book ai didi

javascript - 如何仅在OnInit之后启动iterableDiffer?

转载 作者:行者123 更新时间:2023-11-28 03:36:27 24 4
gpt4 key购买 nike

我的问题是,当我只从数据库中初始化数据时,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);
}

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

感谢您的帮助!

最佳答案

总是可以有一个变量“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);
}
}

关于javascript - 如何仅在OnInit之后启动iterableDiffer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com