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

相关内容

热门资讯

透视资料!智星德州辅助译码插件... 透视资料!智星德州辅助译码插件靠谱吗(透视)pokemomo辅助工具(辅助)原来真的有方法(哔哩哔哩...
透视教程书!来玩app破解版(... 透视教程书!来玩app破解版(透视)sohoo竞技联盟辅助器(辅助)其实真的是有app(哔哩哔哩)1...
透视绝活儿!德州局怎么透视(透... 透视绝活儿!德州局怎么透视(透视)菠萝德州透视脚本(辅助)其实真的有攻略(哔哩哔哩)1、很好的工具软...
透视手册!聚星ai辅助工具收费... 透视手册!聚星ai辅助工具收费多少(透视)哈糖大菠萝免费辅助器(辅助)原来真的是有方法(哔哩哔哩)1...
透视模块!德州局透视脚本下载安... 透视模块!德州局透视脚本下载安装最新版本(透视)菠萝辅助器免费版的特点(辅助)都是一直都是有技巧(哔...
透视操作!werplan怎么作... 透视操作!werplan怎么作必弊(透视)werplan怎么作必弊(辅助)都是一直总是有攻略(哔哩哔...
透视阶段!werplan免费挂... 透视阶段!werplan免费挂下载(透视)poker world辅助器(辅助)一直有神器(哔哩哔哩)...
透视模块!pokemmo手机版... 透视模块!pokemmo手机版透视脚本(透视)pokemmo辅助器脚本下载(辅助)本来一直总是有攻略...
透视法门!拱趴大菠萝十三水作必... 透视法门!拱趴大菠萝十三水作必弊(透视)xpoker辅助工具(辅助)一直存在有神器(哔哩哔哩)1、拱...
透视秘籍!哈糖大菠萝软件下载(... 透视秘籍!哈糖大菠萝软件下载(透视)xpoker怎么作必弊(辅助)总是有神器(哔哩哔哩)1、每一步都...