为什么变量不是更改值?

时间:2020-08-12 11:25:27

标签: angular

组件类中有一个变量public loading: boolean;

还有一种将加载设置为true和false的方法:

public createDocument() {
    try {
        if (this.isOpenDialog) throw 'Dialog already opened!';

        this.loading = true;
        this.isOpenDialog = true;

        this.documentService.loadDocuments(this.application.reglamentid).then((response) => {
            this.documentService.setTypeDocuments(response.typedocuments);
            this.loading = false;

            this.documentDialogFormService
                .open({ title: 'Формирование проекта документа', appid: this.application.appId })
                .subscribe(() => {
                    this.isOpenDialog = false;
                    this.loading = false;
                });
        });
    } catch (e) {
        console.log('ERROR: ' + e);
    }
}

从服务器获取数据时,将其设置为 this.loading = false;

但是在模板{{loading}}中它仍然是true,为什么?

2 个答案:

答案 0 :(得分:1)

这是一个更改检测问题,您可以阅读有关onPush陷阱here的更多信息。

尝试将变量转换为BehaviorSubject。因此,您有一个这样的模板:

{{ loading$ | async }}

您有一个.ts,如下所示:

loading$ = new BehaviorSubject(true);
...
createDocument() {
  ...
  this.loading$.next(true);
  ...
  this.documentService.loadDocuments(this.application.reglamentid).then((response) => {
    this.loading$.next(false);
    ...
  });
}

提示:由于它是BehaviorSubject,因此您可以使用.tsloading$.getValue()文件中同步访问其值。

答案 1 :(得分:0)

将changeDetection设置为OnPush时,更改检测将仅在以下情况下触发:

  • DOM事件
  • 该变量是@Input,其值已更改
  • 变量与async管道一起使用,其值已更改
  • 通过手动触发变更检测

根据您的情况,您可以:

  • 删除changeDetection(或将其设置为Default)
  • 使用async管道(由TheAngularGuy回答)
  • 将ChangeDetectorRef注入构造器中,并在需要时使用.markForCheck()