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、完成福建大菠萝...
透视透视!wepoker智能辅... 透视透视!wepoker智能辅助插件(透视)衢州都莱罗松辅助器(一贯是有辅助神器)-哔哩哔哩1、不需...
透视肯定!wepoker怎么发... 透视肯定!wepoker怎么发冤家牌(透视)芒果辅助器(一直真的是有辅助辅助器)-哔哩哔哩1、进入到...
透视透视!we poker插件... 透视透视!we poker插件(透视)潮友会破解器(好像是有辅助平台)-哔哩哔哩1、点击下载安装,潮...
据相关数据显示!wepoker... 据相关数据显示!wepoker免费钻石(透视)皮皮辅助软件是真的吗(一贯真的有辅助神器)-哔哩哔哩该...
此事备受玩家关注!德州真人透视... 此事备受玩家关注!德州真人透视脚本(透视)山西扣点子的技巧(切实真的是有辅助app)-哔哩哔哩1、在...
透视辅助!wejoker辅助软... 透视辅助!wejoker辅助软件视频(透视)玫瑰大厅辅助(都是存在有辅助修改器)-哔哩哔哩1、下载好...
围绕透视问题!wepoker透... 围绕透视问题!wepoker透视app下载(透视)吉祥填大坑辅助(竟然存在有辅助下载)-哔哩哔哩1、...
透视教程!wepoker透视脚... 透视教程!wepoker透视脚本(透视)wepoker辅助(总是有辅助工具)-哔哩哔哩wepoker...
透视苹果版!wpk俱乐部有没有... 透视苹果版!wpk俱乐部有没有辅助(透视)微信牵手跑胡子辅助工具(竟然是有辅助修改器)-哔哩哔哩1....