Angular 6 中的服务(Services)通常用于跨组件共享数据和方法。Material Design 对话框(Dialogs)是 Angular Material 库中的一个组件,用于创建弹出式界面。要在对话框打开时保持服务状态,可以采取以下几种策略:
这通常是因为对话框关闭时,相关的组件实例被销毁,如果服务中没有持久化状态,那么状态就会丢失。
localStorage
或 sessionStorage
)来持久化状态。BehaviorSubject
来管理状态,它可以记住最新的值,并在订阅时立即发出。以下是一个简单的示例,展示如何在 Angular 6 中使用服务和 Material 对话框来保持状态:
// data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private dataSubject = new BehaviorSubject<any>(null);
data$ = this.dataSubject.asObservable();
setData(data: any) {
this.dataSubject.next(data);
}
getData() {
return this.dataSubject.getValue();
}
}
// app.component.ts
import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DataService } from './data.service';
import { EditDialogComponent } from './edit-dialog/edit-dialog.component';
@Component({
selector: 'app-root',
template: `<button (click)="openDialog()">Open Dialog</button>`
})
export class AppComponent {
constructor(public dialog: MatDialog, private dataService: DataService) {}
openDialog() {
const dialogRef = this.dialog.open(EditDialogComponent);
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.dataService.setData(result);
}
});
}
}
// edit-dialog.component.ts
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DataService } from '../data.service';
@Component({
selector: 'app-edit-dialog',
template: `
<form>
<input [(ngModel)]="data.name" placeholder="Name">
<button (click)="save()">Save</button>
</form>
`
})
export class EditDialogComponent {
data: any;
constructor(
public dialogRef: MatDialogRef<EditDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private dataService: DataService
) {}
save() {
this.dialogRef.close(this.data);
}
}
在这个示例中,DataService
使用 BehaviorSubject
来管理数据状态。当对话框关闭时,它会将新的数据发送回服务,从而保持状态。
通过这种方式,即使对话框关闭,服务中的状态也会被保留,因为 BehaviorSubject
记住了最新的值。
领取专属 10元无门槛券
手把手带您无忧上云