Angular8。我的视图在模型更改时未更新

时间:2020-05-15 15:10:28

标签: javascript angular

在我的应用程序中,更新该视图的模型后,“刷新”视图时遇到了很大的麻烦。主要是在解决API调用并且其响应数据应在该视图上发布之后。

这是我的组件management.component.ts ts文件(我已删除了对该问题不重要的代码):

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-service',
  templateUrl: './service.component.html',
  styleUrls: ['./service.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class ServiceComponent implements OnInit {
  serviceForm: FormGroup;
  notificationStatus: boolean;

  constructor(
    private http: HttpClient
  ) { }

  ngOnInit() {
    this.buildServiceForm();

    // Example endpoint response: { active: false }
    this.getNotificationInfo().subscribe((data: object) => {
      this.notificationStatus = data['active'];
    })
  }

  submit()
  {
    this.notificationStatus = !this.notificationStatus;
  }

  buildServiceForm()
  {
    this.serviceForm = this.formBuilder.group({
      message_de: ['', { validators: [Validators.required] }],
      message_en: ['', { validators: [Validators.required] }]
    });
  }

  getNotificationInfo() {
    return this.http.get(this.apiPath + 'service/notifications');
  }
}

这是HTML中负责显示该模型(按钮标签)的部分:

<form [formGroup]="serviceForm" (ngSubmit)="submit()">
    <mat-form-field class="service__form__textarea">
      <textarea matInput formControlName="message_de"></textarea>
    </mat-form-field>
    <mat-form-field class="service__form__textarea">
      <textarea matInput formControlName="message_en"></textarea>
    </mat-form-field>

    <button>
      <span *ngIf="notificationStatus == false"> Service Off </span>
      <span *ngIf="notificationStatus == true"> Service On </span>
    </button>
</form>

无论何时单击按钮,都会提交一个表单,并且按钮的文本应立即更新(使用ngIf进行更改)。但这只会在我随机单击网站上的其他对象时发生。

我已经尝试过使用changeDetection: ChangeDetectionStrategy.OnPush,但是没有运气。 此处的动画在实践中是什么样子-单击按钮后,其文本仅在单击textarea后才更改,而在单击按钮后不改变: gif animation of the behavior

任何人都知道如何刷新视图,或者为什么视图如此显示?

2 个答案:

答案 0 :(得分:0)

使用ChangeDetectionStrategy.OnPush时,仅当对象引用发生更改时,视图才会更新(请参见angular 2 change detection and ChangeDetectionStrategy.OnPush)。

如果 服务尚未在区域内,则可能需要使用zone.run在区域内运行对notificationStatus的更新(例如,默认Http客户端已在运行)内部区域)。

您还需要使用ChangeDetectorRef手动更新视图,或使用async管道和可观察对象自动更新视图。

答案 1 :(得分:0)

您有两种解决方法:

  1. 使用CDR(快速又脏)

注入您的构造函数ChangeDetectorRef 调用“ cdr.markForCheck();”在Submit方法的末尾。

  1. 转换主题中的notificationStatus 在课程中:

    private notificationStatus $:Subject = new Subject(true);

在提交方法中:

this.notificationStatus$:Subject.next(false);

在html中:

<span *ngIf="(notificationStatus$ | async ) == false"> Service Off </span>

PS:变量名称中的$是可观察/主题的约定

相关问题