Angular应用程序使用未定义的observable不会导致ExpressionChangedAfterItHasBeenCheckedError错误,但它看起来应该会?
创始人
2024-10-30 14:00:24
0

在Angular中,当某个observable的值发生更改时,Angular会运行变更检测器以更新视图。这时可能会遇到ExpressionChangedAfterItHasBeenCheckedError错误,因为更改还没有完全渲染到视图上。

然而,当使用undefinedobservable时,Angular不会运行变更检测器,因为未定义的observable并没有发出任何值。因此,即使值发生更改,Angular也不会更新视图,也不会出现ExpressionChangedAfterItHasBeenCheckedError错误。

以下是示例代码如何创建undefinedobservable和如何订阅它:

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

@Component({
  selector: 'app-my-component',
  template: `
    
{{ value$ | async }}
`, }) export class MyComponent implements OnInit { value$: Observable; ngOnInit() { // Create an undefined observable this.value$ = undefined; // Subscribe to the undefined observable this.value$.subscribe(console.log); // This will not cause ExpressionChangedAfterItHasBeenCheckedError } }

要避免这种情况,可以在创建observable时使用of方法来发出默认值。例如:

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

@Component({
  selector: 'app-my-component',
  template: `
    
{{ value$ | async }}
`, }) export class MyComponent implements OnInit { value$: Observable; ngOnInit() { // Create an observable with a default value this.value$ = of(''); // Subscribe to the observable this.value$.subscribe(console.log); // This will not cause ExpressionChangedAfterItHasBeenCheckedError } }

相关内容

热门资讯

据目击者称!微乐小程序黑科技,... 据目击者称!微乐小程序黑科技,微乐麻辣自建房辅助视频(透视)确实真的是有挂(哔哩哔哩)1、许多玩家不...
六分钟辅助!微乐小程序黑科技,... 六分钟辅助!微乐小程序黑科技,微信小程序微乐辅助器破解版(开挂)一贯是有挂(2026)1、进入到微乐...
备受关注的!微乐小程序黑科技,... 备受关注的!微乐小程序黑科技,小程序微乐陕西挖坑辅助器(透视)其实存在有挂(哔哩哔哩)1、金币登录送...
第1分钟工具!微乐小程序黑科技... 第1分钟工具!微乐小程序黑科技,广西微乐小程序控制器(开挂)竟然是有挂(2026)1、每一步都需要思...
现有说明如下!微乐小程序黑科技... 现有说明如下!微乐小程序黑科技,微信微乐有挂没有(透视)本来存在有挂(哔哩哔哩)1、任何微信微乐有挂...
5分钟插件!微乐小程序免费黑科... 5分钟插件!微乐小程序免费黑科技,微信小程序微乐辅助免费(开挂)总是是有挂(2026)1、许多玩家不...
透视黑科技!微乐小程序黑科技,... 透视黑科技!微乐小程序黑科技,微乐小程序免费黑科技下载方法(透视)竟然存在有挂(哔哩哔哩)1、起透看...
三分钟开挂!微乐小程序黑科技,... 三分钟开挂!微乐小程序黑科技,微乐内蒙古自建房脚本免费下载(开挂)都是有挂(2026)微乐小程序黑科...
现有关情况通报如下!微乐小程序... 现有关情况通报如下!微乐小程序黑科技,收i就微乐小程序游戏破解器(透视)果然真的是有挂(哔哩哔哩)暗...
5分钟安装!微乐小程序免费黑科... 5分钟安装!微乐小程序免费黑科技,微乐小程序授权(开挂)原来是真的挂(2026)1、任何微乐小程序免...