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

相关内容

热门资讯

透视透视"wepok... 透视透视"wepoker私人局开挂视频"hhpoker脚本下载(总是真的是有辅助工具)-哔哩哔哩小薇...
透视规律"wpk真的... 透视规律"wpk真的有透视嘛"wepoker游戏安装教程(其实存在有辅助神器)-哔哩哔哩1、在wep...
出乎意料的是"pok... 出乎意料的是"pokemmo手机脚本辅助器"wepoker透视是真的吗(都是真的有辅助插件)-哔哩哔...
日前"如何下载wpk... 日前"如何下载wpk透视版"hhpoker有没有辅助(好像是真的辅助安装)-哔哩哔哩1、每一步都需要...
有消息称"如何下载德... 有消息称"如何下载德普之星辅助软件"来玩app破解(确实存在有辅助辅助器)-哔哩哔哩1、如何下载德普...
透视神器"we-po... 透视神器"we-poker有人玩吗"we-poker软件(都是是有辅助插件)-哔哩哔哩1、点击下载安...
透视辅助"大菠萝免费... 透视辅助"大菠萝免费辅助"wepoker怎么设置透视(竟然存在有辅助插件)-哔哩哔哩wepoker怎...
透视肯定"约局吧德州... 透视肯定"约局吧德州有挂吗"wepoker有透视吗(确实真的有辅助辅助器)-哔哩哔哩暗藏猫腻,小编详...
透视好友房"wepo... 透视好友房"wepoker游戏的安装教程"hhpoker有没有辅助(其实是真的辅助安装)-哔哩哔哩1...
透视苹果版"wepo... 透视苹果版"wepoker辅助器激活码"德州透视脚本(竟然存在有辅助插件)-哔哩哔哩1、wepoke...