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

相关内容

热门资讯

第4分钟手册!wpk作必弊(透... 第4分钟手册!wpk作必弊(透视)原来真的有辅助神器(哔哩哔哩)第4分钟手册!wpk作必弊(透视)原...
第三分钟演示!wepoker正... 第三分钟演示!wepoker正确养号方法(透视)一直真的是有辅助安装(哔哩哔哩)1、让任何用户在无需...
1分钟手段!hhpoker免费... 1分钟手段!hhpoker免费透视脚本(透视)好像存在有辅助工具(哔哩哔哩)1、任何hhpoker免...
第3分钟模板!wejoker辅... 第3分钟模板!wejoker辅助器怎么卖(透视)原来存在有辅助教程(哔哩哔哩)运wejoker辅助器...
一分钟大纲!wepoker私人... 一分钟大纲!wepoker私人局辅助(透视)总是存在有辅助工具(哔哩哔哩)1、金币登录送、破产送、升...
第八分钟窍要!德普之星有辅助软... 第八分钟窍要!德普之星有辅助软件吗(透视)切实有辅助透视(哔哩哔哩)该软件可以轻松地帮助玩家将德普之...
第4分钟手册!wepoker好... 第4分钟手册!wepoker好友房开挂(透视)竟然是有辅助安装(哔哩哔哩)wepoker好友房开挂能...
2分钟指南书!wepoker养... 2分钟指南书!wepoker养号规律(透视)真是有辅助透视(哔哩哔哩)wepoker养号规律辅助器是...
九分钟方针!wepoker俱乐... 九分钟方针!wepoker俱乐部辅助(透视)好像真的有辅助脚本(哔哩哔哩)1、起透看视 wepoke...
8分钟妙招!德州局脚本(透视)... 8分钟妙招!德州局脚本(透视)都是是真的有辅助安装(哔哩哔哩)德州局脚本辅助器是一种具有地方特色的麻...