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真的假的(透视)玉海楼茶苑app辅助(总是是真的辅助辅助器)-哔哩哔哩1、进入到...
今日!aapoker怎么选牌(... 今日!aapoker怎么选牌(透视)中至常熟辅助(确实存在有辅助下载)-哔哩哔哩中至常熟辅助能透视中...
据通报!aapoker万能辅助... 据通报!aapoker万能辅助器(透视)麻将外卦软件框架模式(原来有辅助app)-哔哩哔哩麻将外卦软...
透视辅助!wpk是真的还是假的... 透视辅助!wpk是真的还是假的(透视)途游辅助软件(真是真的有辅助安装)-哔哩哔哩1、该软件可以轻松...
透视辅助!wepoker透视有... 透视辅助!wepoker透视有吗(透视)都莱辅助器(好像有辅助平台)-哔哩哔哩1、完成都莱辅助器有辅...
透视辅助!wepoker透视底... 透视辅助!wepoker透视底牌脚本(透视)越乡游义乌辅助器小程序(确实是真的辅助安装)-哔哩哔哩亲...
日前!云扑克有透视吗(透视)多... 日前!云扑克有透视吗(透视)多乐手游辅助(果然是有辅助平台)-哔哩哔哩1、多乐手游辅助辅助器安装包、...
透视苹果版!werplan有挂... 透视苹果版!werplan有挂吗(透视)八闽状元郎破解版辅助(都是存在有辅助修改器)-哔哩哔哩1、玩...
据了解!佛手在线有挂吗(透视)... 据了解!佛手在线有挂吗(透视)微信赣牌圈怎么开挂(都是存在有辅助修改器)-哔哩哔哩1、微信赣牌圈怎么...
透视总结!sohoo poke... 透视总结!sohoo poker辅助器(透视)三七互娱辅助器透视开挂(果然有辅助神器)-哔哩哔哩暗藏...