Angular 从服务调用的模式不会显示为模式,而是显示为页面内容
我正在构建一个全局错误处理程序,以便它显示一个引导模式对话框,显示有关错误的详细信息。我有以下设置: 错误模式组件定义了一个名为Angular 从服务调用的模式不会显示为模式,而是显示为页面内容,angular,typescript,bootstrap-4,ng-bootstrap,Angular,Typescript,Bootstrap 4,Ng Bootstrap,我正在构建一个全局错误处理程序,以便它显示一个引导模式对话框,显示有关错误的详细信息。我有以下设置: 错误模式组件定义了一个名为open()的方法,它的模板包含一个按钮(用于调试),该按钮调用open(),一切正常,模式正确显示为绑定文本 ErrorModalComponent代码: import { Component, ViewChild, TemplateRef } from '@angular/core'; import { NgbModal } from '@ng-bootstrap
open()
的方法,它的模板包含一个按钮(用于调试),该按钮调用open()
,一切正常,模式正确显示为绑定文本
ErrorModalComponent代码:
import { Component, ViewChild, TemplateRef } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { GlobalErrorHandler } from './global-error-handler.service';
@Component({
selector: 'app-error-modal',
templateUrl: './error-modal.component.html',
styles: []
})
export class ErrorModalComponent {
private _message: string;
@ViewChild('content') _modalTemplate: TemplateRef<any>;
constructor(private _modalService: NgbModal, private _globalErrorHandler: GlobalErrorHandler) {
this._globalErrorHandler.errorEventSource$.subscribe(errorMessage => {
this._message = errorMessage.toString();
this.open();
});
}
open() {
this._modalService.open(this._modalTemplate);
this._message = "A change test";
}
public get message(): string {
return this._message;
}
}
从'@angular/core'导入{Component,ViewChild,TemplateRef};
从'@ng bootstrap/ng bootstrap'导入{NgbModal};
从“./global error handler.service”导入{GlobalErrorHandler};
@组成部分({
选择器:“应用程序错误模式”,
templateUrl:“./error modal.component.html”,
样式:[]
})
导出类ErrorModalComponent{
私有消息:字符串;
@ViewChild('content')_modalTemplate:TemplateRef
这是引发异常后的模式:
我遇到了完全相同的问题,但设置略有不同。我有一个带有“handleError”函数的globalErrorHandler。显然,该函数在角度区域之外执行
我通过在zone.runguared中运行ngbMdal修复了这个问题
this.zone.runGuarded(() => {
this.modalService = this.injector.get(NgbModal);
const modalRef = this.modalService.open(ErrorComponent);
modalRef.componentInstance.errorMessage = error.message;
modalRef.componentInstance.stack = error.stack;
});
不要忘记构造函数中的注入
private zone: NgZone
将模式的HTML/TS放在专用组件中以使其可重用不是更好吗?您可以使用“componentfactoryresolver”动态加载组件并设置消息属性检查此链接检查loadcomponent()
method@Niladri:组件只是模态,按钮仅用于调试。删除剩下的只是错误模态代码。@Niladri:如果从按钮调用open有效,我是否有理由需要调用类似loadcomponent的东西?这种通用错误模态通常会在整个应用程序中出现,因此如果有的话任何组件中都会发生异常。您可以将异常消息作为参数传递给loadcomponent之类的方法。但是我认为这不是问题所在,您是否调试了this.\u globalErrorHandler.errorEventSource$
observable在抛出异常时是否在组件的构造函数中发出值。您可以在抛出异常的位置共享代码?
this.zone.runGuarded(() => {
this.modalService = this.injector.get(NgbModal);
const modalRef = this.modalService.open(ErrorComponent);
modalRef.componentInstance.errorMessage = error.message;
modalRef.componentInstance.stack = error.stack;
});
private zone: NgZone