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 } }

相关内容

热门资讯

第3分钟诀窍!德州来玩辅助器(... 第3分钟诀窍!德州来玩辅助器(透视)一贯真的有辅助插件(哔哩哔哩)1、德州来玩辅助器脚本辅助下载、德...
6分钟模板!wejoker开挂... 6分钟模板!wejoker开挂(透视)果然有辅助辅助(哔哩哔哩)一、wejoker开挂游戏安装教程牌...
八分钟经验!wepoker透视... 八分钟经验!wepoker透视脚本安卓(透视)一直真的是有辅助下载(哔哩哔哩)进入游戏-大厅左侧-新...
第1分钟窍要!hhpoker透... 第1分钟窍要!hhpoker透视脚本下载(透视)一直真的是有辅助下载(哔哩哔哩)1、第1分钟窍要!h...
第九分钟手段!wpk辅助(透视... 第九分钟手段!wpk辅助(透视)都是真的是有辅助安装(哔哩哔哩)1、第九分钟手段!wpk辅助(透视)...
第五分钟阶段!hh poker... 第五分钟阶段!hh poker透视器下载(透视)总是是真的有辅助教程(哔哩哔哩)亲,关键说明,hh ...
第五分钟指南!wepoker游... 第五分钟指南!wepoker游戏的安装教程(透视)其实真的有辅助脚本(哔哩哔哩)1、玩家可以在wep...
六分钟讲义!wpk辅助是什么(... 六分钟讲义!wpk辅助是什么(透视)竟然有辅助安装(哔哩哔哩)亲,关键说明,wpk辅助是什么透视脚本...
十分钟攻略!we poker插... 十分钟攻略!we poker插件(透视)总是真的是有辅助安装(哔哩哔哩)1、每一步都需要思考,不同水...
6分钟举措!红龙poker有辅... 6分钟举措!红龙poker有辅助吗(透视)都是真的是有辅助神器(哔哩哔哩)1、首先打开红龙poker...