我正在尝试在模式对话框中显示错误,但我完全是 Angular 新手,而且我陷入了困境。
该项目已经使用 bootstrap,所以我尝试使用 NgbModal:
// in ErrorHandler
handleError(error: Error) {
//do other stuff
console.error(error);
this.modalService.open(ErrorDisplayComponent, //problems here
{
//modal options
});
}
这会导致错误:
Uncaught TypeError: Cannot read property 'open' of undefined
at NgbModal.push../node_modules/@ng-bootstrap/ng-bootstrap/fesm5/ng-bootstrap.js.NgbModal.open
似乎 open 方法对 ErrorDisplayComponent 参数不满意。
即使这有效,我也不知道如何将错误变量传递给 ErrorDisplayComponent (但如果我让它工作,我会处理这个问题)。
根据文档 ( https://ng-bootstrap.github.io/#/components/modal/api ),“[open() 方法的内容]可以作为 TemplateRef 或组件类型提供。”
也许我应该尝试使用 TemplateRef 选项(但我不知道如何动态创建 TemplateRef),或者也许这种方法是错误的,我应该做其他事情。但由于我什至不懂行话,所以在谷歌上搜索答案并不那么容易。
有什么想法吗?
提前致谢!
更新:完整代码
ErrorsHandler.ts
import { ErrorHandler, Injectable, Injector} from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ErrorDisplayComponent } from './errors/error-display/error-display.component';
@Injectable()
export class ErrorsHandler implements ErrorHandler {
constructor(private modalService: NgbModal) {
}
handleError(error: Error) {
//console.error(error);
this.modalService.open(ErrorDisplayComponent,
{ ariaLabelledBy: 'modal-basic-title', centered: true, size: 'lg',
windowClass : "newUserModalClass" });
}
}
错误显示.component.ts
import { Component, OnInit } from '@angular/core';
import {NgbActiveModal} from "@ng-bootstrap/ng-bootstrap";
@Component({
selector: 'app-error-display',
templateUrl: './error-display.component.html',
styleUrls: ['./error-display.component.scss']
})
export class ErrorDisplayComponent implements OnInit {
constructor(public activeModal: NgbActiveModal) {
}
ngOnInit() {
}
onClose():void {
this.activeModal.close('closed');
}
onDismiss(reason : String):void {
this.activeModal.dismiss(reason);
}
}
error-display.component.html
<ng-template #content let-modal>
<h1>error-display works!</h1>
</ng-template>
最佳答案
几天前我遇到了这个问题,我找到了解决方案,所以如果有人遇到这个问题,你可以尝试解决它的是在运行时注入(inject) modalService: NgbModal而不是使用构造函数。在这种具体情况下,可以通过以下方式实现注入(inject):
import { ErrorHandler, Injectable, Injector} from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ErrorDisplayComponent } from './errors/error-display/error-
display.component';
@Injectable()
export class ErrorsHandler implements ErrorHandler {
private modalService: NgbModal
constructor(private injector: Injector) {
}
handleError(error: Error) {
this.modalService = this.injector.get(NgbModal);
//console.error(error);
this.modalService.open(ErrorDisplayComponent,
...
在我的例子中,我从另一个服务调用 modalService 但遇到了同样的错误,似乎来自 NgbModal 的 _modalStack: NgbModalStack 属性获取了未定义的值,因此当我在运行时注入(inject)时,服务已定义。
我希望这可以帮助遇到这个问题的人。
您可以阅读下一个文档以更好地了解 NgbModal 功能和 NgbModal 的类组成
https://github.com/ng-bootstrap/ng-bootstrap/blob/master/src/modal/modal.ts
https://ng-bootstrap.github.io/#/components/modal/examples
亲切的问候,
关于Angular 6 错误处理 - 如何在模态中显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53609271/