Angular - 同一组件中的 ExpressionChangedAfterItHasBeenCheckedError [英] Angular - ExpressionChangedAfterItHasBeenCheckedError in same Component

查看:31
本文介绍了Angular - 同一组件中的 ExpressionChangedAfterItHasBeenCheckedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Angular 5 应用程序,带有一个 HttpInterceptor,它在发出请求时通知服务.组件可以订阅此服务以获取此信息.

I have a simple Angular 5 application with a HttpInterceptor that notifies a service when a request is made. Components can subscribe to this service to get this information.

此处有错误的完整示例 => https://stackblitz.com/edit/angular-5b86se

Full example with error here => https://stackblitz.com/edit/angular-5b86se

在我的 AppComponent 中,我想在我的子组件 (HelloComponent) 中发出请求时显示加载指示器.

In my AppComponent I want to show a loading indicator when request are made in my child component (HelloComponent).

import { Component } from '@angular/core';
import { LoadingIndicatorService } from './loading-indicator.service';

@Component({
  selector: 'my-app',
  template: `<div *ngIf="loading" style="color:red">pretend this is loading indicator</div>
<hello name="{{ name }}"></hello>`
})
export class AppComponent  {
  name = 'Angular 5';
   loading: boolean = false;

   constructor(private loadingIndicatorService: LoadingIndicatorService) { 

    loadingIndicatorService
      .onLoadingChanged
      .subscribe(isLoading => this.loading = isLoading);
  }
}

我收到以下错误:

错误:ExpressionChangedAfterItHasBeenCheckedError:表达式有检查后更改.以前的值:'假'.当前值:'真实'.

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.

如果我是正确的,当子组件更改父组件中的值时会出现此错误.

If I'm correct this error appears when a child component changes a value in a parent component.

但我的子组件 (HelloComponent) 仅执行 HttpGet,而 HttpInterceptor 正在通过服务更改父组件 (AppComponent)带有可观察的.

But my child component (HelloComponent) is only doing a HttpGet and the HttpInterceptor is changing the parent component (AppComponent) over a service with an observable.

在这里更改服务不应该是正确的解决方案吗?有人可以解释为什么这不起作用吗?

Shouldn't changing over a service be the correct solution here? Can someone explain why this doesn't work?

推荐答案

它抛出一个错误,因为当调用 onLoadingChanged 时你的变量加载被更新.这意味着您的初始值已更改.

It throws an error because your variable loading gets updated when onLoadingChanged is called. This means your initial value got changed.

我建议您阅读更多关于 这里

I would suggest you to read more about here

对此的一般修复是,

    constructor(private loadingIndicatorService: LoadingIndicatorService,private ref: ChangeDetectorRef) { 
    loadingIndicatorService.onLoadingChanged.subscribe(isLoading => {
       this.loading = isLoading
       this.ref.detectChanges();
    });
 }

这篇关于Angular - 同一组件中的 ExpressionChangedAfterItHasBeenCheckedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆