简体   繁体   English

Angular 4应用程序中的ExpressionChangedAfterItHasBeenCheckedError错误

[英]ExpressionChangedAfterItHasBeenCheckedError Error in Angular 4 Application

I have a HTML that displays some elements that it gets from the database: Here is my HTML: 我有一个HTML,它显示从数据库中获取的一些元素:这是我的HTML:

<div class="home-page">
  <div class="container page">
    <div class="row">

      <div class="col-md-11 col-xs-10">
        <h2>Search</h2>
        <hr>
        <form class="row" name="powerPlantSearchForm" (ngSubmit)="f.valid && emptyAndBindNew(); searchPowerPlants()" #f="ngForm" novalidate>
          <div class="form-group col-xs-3" >
            <label for="powerPlantName">PowerPlant Name</label>
            <input type="text" class="form-control-small" [ngClass]="{ 'has-error': f.submitted && !powerPlantName.valid }" name="powerPlantName" [(ngModel)]="model.powerPlantName" #powerPlantName="ngModel" />
          </div>
          <div class="form-group col-xs-3" >
            <label for="powerPlantType">PowerPlant Type</label>
            <select class="form-control" [(ngModel)]="model.powerPlantType" name="powerPlantType">
              <option value="" disabled>--Select Type--</option>
              <option [ngValue]="powerPlantType" *ngFor="let powerPlantType of powerPlantTypes">
                {{ powerPlantType }}
              </option>
            </select>
          </div>
          <div class="form-group col-xs-3" >
            <label for="organizationName">Organization Name</label>
            <input type="text" class="form-control-small" name="powerPlantOrganization" [(ngModel)]="model.powerPlantOrg" #organizationName="ngModel" />
          </div>
          <div class="form-group col-xs-3" >
            <label for="powerPlantStatus">PowerPlant Active Status</label>
            <select class="form-control" [(ngModel)]="model.powerPlantStatus" name="powerPlantStatus">
              <option value="" disabled>--Select Status--</option>
              <option [ngValue]="powerPlantStatus" *ngFor="let powerPlantStatus of powerPlantStatuses">
                {{ powerPlantStatus }}
              </option>
            </select>
          </div>
          <div class="form-group col-md-3 col-xs-4">
            <button [disabled]="loading" class="btn btn-primary">Search</button>
            <img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
            <button type="button" (click)="resetForm()" class="btn btn-primary">Reset</button>
          </div>
        </form>
        <hr>
        <div>

          <ul id="infinite-scroller" appInfiniteScroller scrollPerecnt="70" [immediateCallback]="true" [scrollCallback]="scrollCallback">
            <li *ngFor="let powerPlant of powerPlants">{{powerPlant.powerPlantName}}</li>
          </ul>

        </div>
      </div>
    </div>
  </div>
</div>

As we can see I'm calling 2 different functions in my Typescript which is as below: 如我们所见,我在TypeScript中调用了2个不同的函数,如下所示:

import { Component, OnInit } from '@angular/core';

import { PowerPlantService, UserService } from '../shared';
import { User } from '../shared/models/user.model';
import { PowerPlant } from '../shared/models/powerplant.model';
import {PowerPlantSearchParams} from '../shared/models/powerplantsearchparams.model';

@Component({
  selector: 'app-home-page',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  // Represents the PowerPlantTypes
  powerPlantTypes = ['RampUpType', 'OnOffType'];
  // Represents the status of a PowerPlant
  powerPlantStatuses = ['Active & Disabled', 'Active', 'Disabled'];
  // Represents the search form
  model: any = {};
  // represents the list of PowerPlant data
  powerPlants: PowerPlant[] = [];
  scrollCallback;

  currentPage = 1;

  // Indicates if the searchButton was clicked or not!
  isSearchButtonClicked = false;

  constructor(private powerPlantService: PowerPlantService) {
    // this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
    // Set the initial values for the drop down fields in the UI
    this.resetForm();

    this.scrollCallback = this.searchPowerPlants.bind(this);
  }

  ngOnInit() {}

  resetForm() {
    this.model.powerPlantOrg = '';
    this.model.powerPlantName = '';
    this.model.powerPlantType = '';
    this.model.powerPlantStatus = '';
  }

  emptyAndBindNew() {
    this.isSearchButtonClicked = true;
  }

  searchPowerPlants() {
    if (this.isSearchButtonClicked === true) {
      this.isSearchButtonClicked = false;
      // Reset the old entries
      this.powerPlants = [];
      this.currentPage = 1;
      this.searchPowerPlants();
    } else {
      alert('page number is ' + this.currentPage);
      const powerPlantSearchParams = new PowerPlantSearchParams(
        this.model.powerPlantType,
        this.model.powerPlantOrg,
        this.model.powerPlantName,
        this.model.powerPlantStatus);

      return this.powerPlantService.searchPowerPlants(powerPlantSearchParams, this.currentPage).do(this.processData);
    }
  }

  private processData = (newPowerPlants) => {
    this.currentPage++;
    // this.powerPlants = this.powerPlants.concat(newPowerPlants.json());
    this.powerPlants = this.powerPlants.concat(newPowerPlants);
  }
}

I get a very strange error in my Angular application: 我在Angular应用程序中遇到一个非常奇怪的错误:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''.

The error happens in this line: 该行中发生错误:

        <li *ngFor="let powerPlant of powerPlants">{{powerPlant.powerPlantName}}</li>

What is the problem with my piece of code and how to get rid of this error: Here is what the whole thing is about! 我的代码段是什么问题,以及如何消除此错误:这就是全部内容!

  1. The user is presented with a Search form where he can enter his different search criteria 向用户显示“搜索”表单,他可以在其中输入其不同的搜索条件

  2. When the user clicks Search button, I call a REST API backend and fetch some data (I limit the fetch to 10 entries). 当用户单击“搜索”按钮时,我将调用REST API后端并获取一些数据(将获取限制为10个条目)。

  3. When the user scrolls down on the result entries, I load him additional 10 entries and this keeps going on as long as I can find more data. 当用户向下滚动结果条目时,我会向他加载另外的10个条目,只要我能找到更多数据,它就会一直持续下去。

  4. Now if the user wishes to search for some other criteria, he enters again the search fields and submits the form. 现在,如果用户希望搜索其他条件,则可以再次输入搜索字段并提交表单。

  5. When the form is submitted, I have to reset all the old search results and populate the new entries that I get from the backend REST API! 提交表单后,我必须重置所有旧的搜索结果,并填充从后端REST API获得的新条目!

The above code does that, but it runs into error after I do point number 4! 上面的代码可以做到这一点,但是在执行第4点后,它就会出错! Any ideas? 有任何想法吗? Here is a screenshot of the error that I face! 这是我遇到的错误的屏幕截图!

EDIT: The PowerPlantsService contains the following method: 编辑:PowerPlantsService包含以下方法:

private generateData() {
    const powerPlantArray: PowerPlant[] = [];
    for (let i = 0; i < 20; i++) {
      if (i % 2 === 0) {
        const p: PowerPlant = {
          powerPlantId: i,
          powerPlantName: `PowerPlant ${i}`,
          minPower: 100,
          maxPower: 200,
          powerPlantType: 'OnOffType'
        };
        powerPlantArray.push(p);
      } else {
        const p: PowerPlant = {
          powerPlantId: i,
          powerPlantName: `PowerPlant ${i}`,
          minPower: 100,
          maxPower: 200,
          powerPlantType: 'RampUpType',
          rampPowerRate: 10,
          rampRateInSeconds: 2
        };
        powerPlantArray.concat(p);
      }
    }
    return powerPlantArray;
  }

  searchPowerPlants(searchParams: PowerPlantSearchParams, page: number): Observable<any> {
    const params: string[] = [];
    // pageNumber is mandatory
    if (page) {
      params.push(`page=${page}`);
    } else {
      params.push(`page=1`);
    }
    // All the other fields are optional
    if (searchParams.powerPlantStatus === 'Active') {
      params.push(`onlyActive=true`);
    } else if (searchParams.powerPlantStatus === 'Disabled') {
      params.push(`onlyActive=false`);
    }
    if (searchParams.powerPlantType) {
      params.push(`powerPlantType=${searchParams.powerPlantType}`);
    }
    if (searchParams.powerPlantOrg) {
      params.push(`org=${searchParams.powerPlantOrg}`);
    }
    if (searchParams.powerPlantName) {
      params.push(`name=${searchParams.powerPlantName}`);
    }
    // return this.apiService.get(`${this.allPowerPlantsURL}?${params.join('&')}`);
    return Observable.of(this.generateData());
  }

在此处输入图片说明

I'm rather guessing your error comes from the last line of your last function. 我想您的错误来自上一个函数的最后一行。 Could you try this instead ? 你能试试看吗?

this.setTimeout(() => this.powerPlants = this.powerPlants.concat(newPowerPlants));

EDIT In your service, replace the const powerPlantArray with a let powerPlantArray : 编辑在您的服务中,用let powerPlantArray替换const powerPlantArray let powerPlantArray

private generateData() {
  let powerPlantArray: PowerPlant[] = [];
  for (let i = 0; i < 20; i++) {
    if (i % 2 === 0) {
      const p: PowerPlant = {
        powerPlantId: i,
        powerPlantName: `PowerPlant ${i}`,
        minPower: 100,
        maxPower: 200,
        powerPlantType: 'OnOffType'
      };
      powerPlantArray.push(p);
    } else {
      const p: PowerPlant = {
        powerPlantId: i,
        powerPlantName: `PowerPlant ${i}`,
        minPower: 100,
        maxPower: 200,
        powerPlantType: 'RampUpType',
        rampPowerRate: 10,
        rampRateInSeconds: 2
      };
      powerPlantArray.concat(p);
    }
  }
  return powerPlantArray;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误错误:Angular 5中的ExpressionChangedAfterItHasBeenCheckedError - ERROR Error: ExpressionChangedAfterItHasBeenCheckedError in Angular 5 Angular 加载错误 ExpressionChangedAfterItHasBeenCheckedError - Angular Loading Error ExpressionChangedAfterItHasBeenCheckedError 错误:ExpressionChangedAfterItHasBeenCheckedError - ERROR : ExpressionChangedAfterItHasBeenCheckedError Angular 8 在页面加载后添加 class 错误:ExpressionChangedAfterItHasBeenCheckedError - Angular 8 add class after page load Error: ExpressionChangedAfterItHasBeenCheckedError 角度抛出ExpressionChangedAfterItHaHasBeenCheckedError - Angular throws ExpressionChangedAfterItHasBeenCheckedError 角度中的 getter 值抛出 ExpressionChangedAfterItHasBeenCheckedError - getter value in angular throws ExpressionChangedAfterItHasBeenCheckedError 离子如何修复“ExpressionChangedAfterItHasBeenCheckedError”错误? - Ionic how to fix “ExpressionChangedAfterItHasBeenCheckedError” error? Angular:尝试禁用按钮时出现 ExpressionChangedAfterItHasBeenCheckedError - Angular: ExpressionChangedAfterItHasBeenCheckedError when trying to disable button 在进度条中使用随机数时出现 Angular ExpressionChangedAfterItHasBeenCheckedError - Angular ExpressionChangedAfterItHasBeenCheckedError while using random numbers in progress bar 面临错误:ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改 - Facing Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM