要在Angular 6的模态框中显示错误,可以按照以下步骤进行操作:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ErrorHandlingService {
private errorMessageSubject = new BehaviorSubject(null);
errorMessage$ = this.errorMessageSubject.asObservable();
constructor() { }
displayError(message: string) {
this.errorMessageSubject.next(message);
}
}
import { Component, OnInit } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { ErrorHandlingService } from 'path-to-error-handling-service';
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
closeResult: string;
constructor(private modalService: NgbModal, private errorHandlingService: ErrorHandlingService) { }
ngOnInit() {
this.errorHandlingService.errorMessage$.subscribe(message => {
if (message) {
this.openModal(message);
}
});
}
open(content) {
this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private openModal(message: string) {
this.modalService.open(ModalContentComponent, { size: 'lg' }).componentInstance.message = message;
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
import { Component, Input } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-modal-content',
template: `
Error
{{ message }}
`
})
export class ModalContentComponent {
@Input() message: string;
constructor(public activeModal: NgbActiveModal) { }
}
import { Component } from '@angular/core';
import { ErrorHandlingService } from 'path-to-error-handling-service';
@Component({
selector: 'app-root',
template: `
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private errorHandlingService: ErrorHandlingService) { }
triggerError() {
this.errorHandlingService.displayError('Something went wrong');
}
}
通过以上步骤,当调用triggerError()
方法时,错误处理服务将显示一个带有错误消息的模态框。