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

相关内容

热门资讯

透视了解!wepoker怎么挂... 透视了解!wepoker怎么挂底牌(透视)心悦辅助(原来存在有辅助软件)-哔哩哔哩1.心悦辅助 选牌...
为切实保障!wepoker手机... 为切实保障!wepoker手机插件(透视)川娱竞技辅助(一贯真的有辅助辅助器)-哔哩哔哩1、点击下载...
透视玄学!pokerrrr2辅... 透视玄学!pokerrrr2辅助(透视)微信插件激活码(真是真的是有辅助插件)-哔哩哔哩1、微信插件...
透视新版!拱趴大菠萝机器人(透... 透视新版!拱趴大菠萝机器人(透视)越乡游双扣辅助器(果然是真的辅助安装)-哔哩哔哩1、起透看视 越乡...
透视肯定!aapoker如何设... 透视肯定!aapoker如何设置胜率(透视)吉祥填大坑怎么用插件(果然真的有辅助神器)-哔哩哔哩1、...
无独有偶!fishpoker透... 无独有偶!fishpoker透视底牌(透视)新九游辅助软件(真是是真的辅助插件)-哔哩哔哩运新九游辅...
这一现象值得深思!德州局怎么透... 这一现象值得深思!德州局怎么透视(透视)微信小程序辅助有哪些(总是真的是有辅助辅助器)-哔哩哔哩1、...
透视ai代打!xpoker辅助... 透视ai代打!xpoker辅助怎么用(透视)手机游戏挂机辅助软件(都是有辅助插件)-哔哩哔哩1、进入...
透视最新!xpoker透视辅助... 透视最新!xpoker透视辅助(透视)福建兄弟13水插件(切实存在有辅助下载)-哔哩哔哩1、用户打开...
为切实保障!wepoker私人... 为切实保障!wepoker私人辅助器(透视)赣湘互娱辅助(总是有辅助修改器)-哔哩哔哩该软件可以轻松...