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、这是跨平台...
透视游戏!werplan怎么作... 透视游戏!werplan怎么作必弊(透视)哈局十三张元华辅助(一贯真的有辅助app)-哔哩哔哩1、玩...
透视大纲!pokemmo脚本辅... 透视大纲!pokemmo脚本辅助器(透视)哈糖大菠萝挂(辅助)好像一直总是有软件(哔哩哔哩)1、进入...
据公告内容!wepoker插件... 据公告内容!wepoker插件下载(透视)渝都麻将辅助器(都是真的是有辅助辅助器)-哔哩哔哩1、渝都...
透视手筋!epoker免费透视... 透视手筋!epoker免费透视脚本(透视)pokermaster辅助器(辅助)原来一直都是有软件(哔...
现就发布提示!德普之星有透视辅... 现就发布提示!德普之星有透视辅助吗(透视)悟空大厅怎么挂辅助(切实真的有辅助平台)-哔哩哔哩悟空大厅...
透视烘培!pokemmo手机辅... 透视烘培!pokemmo手机辅助软件(透视)sohoo poker辅助(辅助)竟然存在有神器(哔哩哔...
辅助透视!aapoker俱乐部... 辅助透视!aapoker俱乐部靠谱吗(透视)四川游戏家园通用辅助(竟然真的有辅助下载)-哔哩哔哩辅助...
透视指南书!智星德州插件202... 透视指南书!智星德州插件2024最新版(透视)约局吧游戏挂(辅助)都是真的是有脚本(哔哩哔哩)1、进...
不少玩家反映!佛手在线大菠萝技... 不少玩家反映!佛手在线大菠萝技巧(透视)开心泉州小程序有挂吗(一贯有辅助安装)-哔哩哔哩1、任何开心...