gpt4 book ai didi

angular - Angular 4 中的 ChangeDetector Ref 错误

转载 作者:太空狗 更新时间:2023-10-29 17:51:44 24 4
gpt4 key购买 nike

我和其他人有类似的错误。但我真的可以解决它。错误是 ERROR Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges. 我已经看过其他人提出的类似问题,但我的应用没有好的答案。我想检测变化,比如是否有 5 秒的新数据。我希望它出现在我的浏览器中。所以我使用了更改的 Detector ref,但它给出了错误。

    export class UsersListComponent implements OnInit {
closeResult: string;
users: any;
subscription: Subscription;
modalRef: NgbModalRef;
intervalHolder: any;
constructor(private modalService: NgbModal,
private usersService: UsersService,
private router: Router,
private ref: ChangeDetectorRef
) {

ref.detach();
setInterval(() => {
if ( this.ref !== null &&
this.ref !== undefined &&
! (this.ref as ViewRef).destroyed) {
this.ref.detectChanges();
}
}, 5000);


}

ngOnInit() {
this.getAllUsers();
}

getAllUsers() {
this.subscription = this.usersService.getAll()
.subscribe(
(data:any) => {
this.users = data.users;
console.log(data);
},
error => {
alert("Error");
});
}

onCreateUser(form: NgForm){
const name = form.value.name;
const email = form.value.email;
const password = form.value.password;
console.log(name);
this.usersService.addUser(name, email, password)
.subscribe(
data => {
alert("User Created");
console.log(data);
this.modalRef.close();
this.usersService.clearCache();
this.getAllUsers();
},
error => {
alert("Error Adding");
console.log(error);
});
}

ngOnDestroy() {
clearInterval(this.intervalHolder);
this.subscription.unsubscribe()
}

最佳答案

请记住,您还必须在 ngOnDestroy 上清除 setInterval

export class UsersListComponent implements OnInit {
closeResult: string;
users: any;
subscription: Subscription;
modalRef: NgbModalRef;

intervalHolder: any;

constructor(private modalService: NgbModal,
private usersService: UsersService,
private router: Router,
private ref: ChangeDetectorRef
) {

ref.detach();
this.intervalHolder = setInterval(() => {
this.ref.detectChanges(); // you don't need this detectChanges, you can just use the one in the getAllUsers and everything will work as expected
this.getAllUsers();
}, 5000);

}

ngOnDestroy() {
this.subscription.unsubscribe();
clearInterval(this.intervalHolder);
}

getAllUsers() {
this.subscription = this.usersService.getAll()
.subscribe(
(data:any) => {
this.users = data.users;
// This will help you with the initial load delay.
this.ref.detectChanges();
console.log(data);
},
error => {
alert("Error");
});
}

}

更新getAllUsers 中手动运行 detectChanges 以消除初始延迟。

关于angular - Angular 4 中的 ChangeDetector Ref 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780950/

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