ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改

Posted

技术标签:

【中文标题】ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改【英文标题】:ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked 【发布时间】:2018-05-10 13:12:21 【问题描述】:
import  Component  from '@angular/core'; import  PeriodsService  from '../periods';

@Component(
    selector: 'app-control-panel',
    templateUrl: './control-panel.component.html',
    styleUrls: ['./control-panel.component.css'] 
) 
export class ControlPanelComponent 
    private selectedPeriod;
    private selectedPosition;

    constructor(
        private periodsService: PeriodsService,
        private positionsService: PositionsService,
        private classifierService: ClassifierService
    ) 
        this.periodsService.periodChange.subscribe(period => 
            this.selectedPeriod = period;
        );
    

    get periodTitle() 
        return this.selectedPeriod.p_display_name;
    

    


    //Template file: control-panel.component.html
    periodTitle

块引用

【问题讨论】:

【参考方案1】:

使用ChangeDetectorRef

import  Component, ChangeDetectorRef  from '@angular/core'; import  PeriodsService  from '../periods';

@Component(
    selector: 'app-control-panel',
    templateUrl: './control-panel.component.html',
    styleUrls: ['./control-panel.component.css'] 
) 
export class ControlPanelComponent 
    private selectedPeriod;
    private selectedPosition;

    constructor(
        private periodsService: PeriodsService,
        private positionsService: PositionsService,
        private classifierService: ClassifierService,
        private cdRef: ChangeDetectorRef ,
    ) 

    

    ngOnInit()
        this.periodsService.periodChange.subscribe(period => 
            this.selectedPeriod = period;
            this.cdRef.detectChanges();
        );
    
    get periodTitle() 
        return this.selectedPeriod.p_display_name;
    

    


    //Template file: control-panel.component.html
    periodTitle

【讨论】:

【参考方案2】:

ChangeDetectorRef.detectChanges() 通过在孩子和父母之间共享数据

import  Component,
     Input,
     ChangeDetectionStrategy,
     ChangeDetectorRef  from '@angular/core';

@Component(
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
 )



export class ChildComponent 
@Input() data: string[];

constructor(private cd: ChangeDetectorRef) 

    refresh() 
    this.cd.detectChanges();
   
 

【讨论】:

以上是关于ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改的主要内容,如果未能解决你的问题,请参考以下文章

错误 [ERR_UNHANDLED_ERROR]:未处理的错误。 (“不正确的论点”)

[PHP] error_reporting可以屏蔽Fatal error错误

redis错误error记录

在 MySQL 中出现 ERROR 1701、ERROR 1452 和 ERROR 1305 错误 - 需要一些专业知识

Error MSB4175 错误

打开一些网址会出现Network Error (tcp_error)的错误