Для рабочего примера StackBlitz
Поместите это в папку / shared или / services на корневом уровне.
Услуга:
import { Observable } from 'rxjs';
import { MessagesComponent } from './messages.component';
import { MatDialogRef, MatDialog } from '@angular/material';
import { Injectable } from '@angular/core';
@Injectable()
export class MessagesService {
dialogRef: MatDialogRef<MessagesComponent>;
constructor(private dialog: MatDialog) { }
public openDialog(title: string, message: string): Observable<any> {
this.dialogRef = this.dialog.open(MessagesComponent);
this.dialogRef.componentInstance.title = title;
this.dialogRef.componentInstance.message = message;
return this.dialogRef.afterClosed();
// Nothing can live after afterClosed.
}
}
Component.ts
import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
selector: 'app-messages',
templateUrl: './messages.component.html'
})
export class MessagesComponent implements OnInit {
public title: string;
public message: string;
constructor(
private dialogRef: MatDialogRef<MessagesComponent>,
) { }
private closeWithTimer() {
setTimeout (() => {
this.dialogRef.close();
}, 2000);
}
ngOnInit() {
this.closeWithTimer();
}
}
HTML:
<h1 mat-dialog-title>{{title}}!</h1>
<div mat-dialog-content>{{message}}</div>
Вызов из какого-то компонента в вашей вселенной:
constructor(
private httpService: HttpService,
public dialogRef: MatDialogRef<AddMemberComponent>, // Used by the html component.
private messagesService: MessagesService,
public formErrorsService: FormErrorsService
) { }
this.httpService.addRecord(this.membersUrl, enteredData)
.subscribe(
res => {
this.success();
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.message);
this.handleError(err);
}
);
В нижней части этого компонента ts:
private success() {
this.messagesService.openDialog('Success', 'Database updated as you wished!');
}
private handleError(error) {
this.messagesService.openDialog('Error addm1', 'Please check your Internet connection.');
}