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

相关内容

热门资讯

透视助手!hhpoker买挂(... 透视助手!hhpoker买挂(透视)开挂辅助技巧(好像存在有挂)-哔哩哔哩1、下载好hhpoker买...
有玩家发现!hhpoker有透... 有玩家发现!hhpoker有透视功能吗,广西老友玩有破解视频,原来有挂(分享线上教程)-哔哩哔哩1、...
透视工具!sohoo poke... 透视工具!sohoo poker辅助,sohoo poker辅助,法子教程(其实真的有挂)-哔哩哔哩...
透视系统!aapoker透视脚... 透视系统!aapoker透视脚本入口(透视)开挂辅助技巧(真是真的是有挂)-哔哩哔哩透视系统!aap...
透视软件!拱趴大菠萝机器人,上... 透视软件!拱趴大菠萝机器人,上饶中至脚本修改,果然有挂(总结实用技巧)-哔哩哔哩上饶中至脚本修改辅助...
辅助透视!约局吧游戏挂,wep... 辅助透视!约局吧游戏挂,wepoker买脚本靠谱吗,步骤教程(确实是有挂)-哔哩哔哩1)wepoke...
透视神器!wejoker透视方... 透视神器!wejoker透视方法(透视)开挂辅助器(确实有挂)-哔哩哔哩wejoker透视方法是一种...
透视真的!德普之星透视辅助插件... 透视真的!德普之星透视辅助插件,心悦辅助透视脚本,一贯存在有挂(专业科技教程)-哔哩哔哩1、实时心悦...
透视科技!wepoker智能辅... 透视科技!wepoker智能辅助插件,有哪些免费的wpk辅助码,步骤教程(原来真的有挂)-哔哩哔哩透...
透视插件!wepoker辅助视... 透视插件!wepoker辅助视频(透视)开挂辅助方法(切实是真的挂)-哔哩哔哩1、wepoker辅助...