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

相关内容

热门资讯

透视系统!wepokerplu... 透视系统!wepokerplus辅助(透视)开挂辅助方法(一贯真的是有挂)-哔哩哔哩1、下载好wep...
透视有挂!we-poker辅助... 透视有挂!we-poker辅助,wejoker内置辅助,手段教程(本来有挂)-哔哩哔哩1)wejok...
透视插件!德扑HHpoker有... 透视插件!德扑HHpoker有挂吗(透视)开挂辅助软件(总是是有挂)-哔哩哔哩暗藏猫腻,小编详细说明...
透视黑科技!菠萝辅助器免费版的... 透视黑科技!菠萝辅助器免费版的特点,hhpoker透视脚本,教材教程(好像存在有挂)-哔哩哔哩1、全...
透视开挂!哈糖大菠萝可以开挂吗... 透视开挂!哈糖大菠萝可以开挂吗(透视)开挂辅助脚本(原来是真的挂)-哔哩哔哩透视开挂!哈糖大菠萝可以...
透视计算!sohoopoker... 透视计算!sohoopoker辅助,hhpoker辅助码,操作教程(原来是真的挂)-哔哩哔哩1、打开...
透视漏洞!wpk透视工作室(透... 透视漏洞!wpk透视工作室(透视)开挂辅助神器(好像是有挂)-哔哩哔哩wpk透视工作室是一种具有地方...
透视有挂!wepoker俱乐部... 透视有挂!wepoker俱乐部辅助,wepoker私局辅助,方式教程(原来有挂)-哔哩哔哩1、在we...
透视ios!哈糖大菠萝可以开挂... 透视ios!哈糖大菠萝可以开挂吗(透视)开挂辅助攻略(竟然真的有挂)-哔哩哔哩1)哈糖大菠萝可以开挂...
透视工具!xpoker辅助,w... 透视工具!xpoker辅助,wepoker免费脚本,烘培教程(总是是有挂)-哔哩哔哩一、wepoke...