我正在try 显示/隐藏基于服务上的变量的ng容器.应该在全局错误处理程序中更改该值,该处理程序应该捕获应用程序上的所有异常.

在我的服务中,我创建了一个变量,将我的BehaviorSubject公开为可观察的.

export class ErrorsService {

  private notify = new BehaviorSubject(false);

  // Subscribe to cast in the component
  cast = this.notify.asObservable();

  // Change notify value
  notifyError(){
    this.notify.next(true);
  }

  constructor() { }

}

我将此服务注入到我的全局错误处理程序中,以便按如下方式调用通知错误():

export class GlobalErrorHandler implements ErrorHandler {

  constructor(private errorService: ErrorsService) { }
  handleError(error: any) {

    // Notify subscribers
    this.errorService.notifyError();
     
    //continue handling the error

    }
  }

在我的组件中,我使用相同的服务订阅变量"cast"并更改本地变量show.

export class ErrorsBlockComponent implements OnInit {

  show = false;
  constructor(private errorsService:ErrorsService) {}

  ngOnInit(): void {
    this.errorsService.cast.subscribe(value=>{
      this.show = value;
    });
  }
  
}

最后,我的组件的html如下所示

 <ng-container *ngIf="show">There is an Error!</ng-container>

例如,直到我点击一个按钮!(应用程序中的任何按钮),视图才会更新.Show值更改为True,但视图似乎没有更新.

我的问题是,当服务价值按预期更新时,为什么视图没有更新?当我使用console.log(Value)时,我可以看到该值变为真,但在我按下按钮之前,UI上没有任何react .


最新情况:

我在StackBlitz上复制了这个问题

https://stackblitz.com/edit/angular-ivy-j7thwx?file=src/app/app.component.ts

我还使用了ChangeDetectorRef.DetectChanges(),它似乎解决了这个问题.然而,我想知道为什么没有它就不能工作,因为这个项目是为了学习的目的.

推荐答案

这是因为您的代码运行在Angular 区域之外.如果在Angular 区域之外发生了任何事情,您需要运行NgZone来推动您的更改.

下面是判断代码行是否在NgZone中的方法.

NgZone.isInAngularZone()

在你的情况下,你可以做

  ngOnInit() {
    console.log('Outside subscription Is in angular zone: ' + NgZone.isInAngularZone());
    // Subscribe to error service
    this.errorsService.cast.subscribe((value) => {
      this.show = value;
      console.log('Within subscription Is in angular zone: ' + NgZone.isInAngularZone());

    });

    // The getSomething call is going to throw an error
    this.anotherService
      .getSomthing()
      .subscribe((result) => (this.result = result));
  }

查看更新后的stackblitz

要触发您可以执行的更改

this.ngZone.run( () => {
     this.show = value;
  });

如第here章所述

Angular相关问答推荐

Angular 16未知参数:独立

Angular 服务错误处理响应类型=BLOB

ANGLE DI useFactory将参数传递给工厂函数

是否自动处理Angular /RxJS观测数据的取消订阅

ANGLING HTTP.GET()返回包含数据的数组

Angular 显示来自文字数组的SVG路径

无法在Mat-SideNav中绑定模式

有角.服务.模块构建失败.无法读取未定义的属性(读取文件)

PrimeNG 避免在同一位置使用不同键的 cogo toast 重叠

需要做什么才能使 ErrorHandler 正常工作?

ngx-bootstrap modal:如何从模态中获取返回值?

Angular 2: Debounce(ngModelChange)?

Angular 2 - 事件列表

如何将服务变量传递到 Angular Material 对话框?

如何使用 Bootstrap 4 flexbox 填充可用内容?

带有 Angular 的 Font Awesome 5

angular 2 http withCredentials

在 Angular rxjs 中,我什么时候应该使用 `pipe` 与 `map`

如何从 EventEmitter 函数返回值?

找不到@angular/common/http模块