我正在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(),它似乎解决了这个问题.然而,我想知道为什么没有它就不能工作,因为这个项目是为了学习的目的.