角度保存/恢复组件状态

时间:2019-05-12 20:35:34

标签: angular

我正在开发具有多选项卡布局的angular 7应用程序。每个选项卡都包含一个组件,可以引用其他嵌套的组件。

当用户选择一个新的/另一个选项卡时,当前选项卡上显示的组件将被破坏(我不只是隐藏它们,而且我遵循了这种模式,因为打开的选项卡可能很多,这似乎是一个更快的解决方案对我来说)。由于加载组件的成本可能很高(可能是从API检索到的大量数据),所以我试图将每个组件状态保持在选项卡容器中(在整个应用程序生命周期中保持活动状态)。

一切都按预期进行,但是我想我已经使用了很多代码来满足自己的需求,我希望一切都可以变得更简单(并且不易出错)。

下面是有关我如何做到的摘录。首先,我创建了一个抽象类,选项卡中的每个组件都应扩展。

export abstract class TabbedComponent implements OnInit, OnDestroy {
  abstract get componentName(): string;

  tab: LimsTab;
  host: TabComponent;
  private _componentInitialized = false;

  constructor(
    private _host: TabComponent,
  ) {
    this.host = _host;
  }

  get componentInitialized(): boolean {
    return this._componentInitialized;
  }

  ngOnInit(): void {
    this.tab = this.host.tab;
    this.loadDataContext();
    this._componentInitialized = true;
  }

  ngOnDestroy(): void {
    this.saveDataContext();
  }

  get dataContext() {
    return this.tab.dataContext;
  }

  protected abstract saveDataContext(): void;
  protected abstract loadDataContext(): void;
}

loadDataContextsaveDataContext在具体组件中实现,并且包含用于保存/检索组件实例值的逻辑。此外,我已经使用_componentInitialized来了解组件何时调用了其生命周期挂钩OnInit:组件可以从其父那里接收@Input,并且ngOnChangesOnInit之前被触发

以下是具体实现的示例:

@Component({
   ...
})
export class MyComponent extends TabbedComponent implements OnChanges {

  private qualityLotTests: QualityLotTestListItem[];
  private _selectedTest: QualityLotTestListItem;

  @Input()
  selectedQualityLot: string;

  @Output()
  selectedTest: EventEmitter<QualityLotTestListItem> = new EventEmitter<QualityLotTestListItem>();

  constructor(_host: TabComponent, private qualityLotService: QualityLotService) {
    super(_host);
  }

  get componentName(): string {
    return 'QualityLotTestListComponent';
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.componentInitialized) {
      // before calling loadData I need to restore previous data (if any) 
      // this allow me to undestrand if loaded data filters has changed 
      // I know I restored it if onInit has executed

      // if componentInitialized -> onInit has been executed and input parameters passed from parent are changed
      this.loadData();
    }
  }

  protected saveDataContext(): void {
    this.dataContext[this.componentName].selectedQualityLot = this.selectedQualityLot;
    this.dataContext[this.componentName].state = this.state;
    this.dataContext[this.componentName].qualityLotTests = this.qualityLotTests;
    this.dataContext[this.componentName].selectedSampleTestIDs
        = this.selectedSampleTestIDs;
    this.dataContext[this.componentName]._selectedTest = this._selectedTest;

  }

  protected loadDataContext(): void {
    let previouslySelectedQualityLot: string;

    if (this.dataContext[this.componentName]) {
      previouslySelectedQualityLot = this.dataContext[this.componentName].selectedQualityLot;
      this.state = this.dataContext[this.componentName].state || this.state;
      this.qualityLotTests = this.dataContext[this.componentName].qualityLotTests;
      this._selectedTest = this.dataContext[this.componentName]._selectedTest;      
    } else {
      this.dataContext[this.componentName] = {};
    }
    this.selectedTest.emit(this._selectedTest);

    if (this.qualityLotTests && previouslySelectedQualityLot === this.selectedQualityLot) {
      this.dataStateChange(<DataStateChangeEvent>this.state);
    } else {
      this.loadData();
    }
  }


  loadData(): void {
    if (this.selectedQualityLot) {
      this.loading = true;
      this.qualityLotService
        .getQualityLotTests(this.selectedQualityLot)
        .subscribe(
          qualityLotTests => {
            this.qualityLotTests = qualityLotTests;
            this.gridData = process(this.qualityLotTests, this.state);
            this.loading = false;
          },
          error => (this.errorMessage = <any>error)
        );
    } else {
      this.qualityLotTests = null;
      this.gridData = null;
      this.state = {
        skip: 0,
        take: 10
      };
      this.selectedSampleTestIDs = [];
      this.selectedTest.emit(null);
    }
  }

  public dataStateChange(state: DataStateChangeEvent): void {
    this.loading = true;
    this.state = state;
    this.gridData = process(this.qualityLotTests, this.state);
    this.loading = false;
  }
}

您认为我如何改进上面的代码?

我已经在https://stackblitz.com/edit/angular-tabbed-app

处加载了我的应用程序的摘录

1 个答案:

答案 0 :(得分:1)

我们可以看到Plunkr进行澄清吗?

我认为可以利用三种常见的模式来保持状态而无需所有对象继承。

  1. 容器/表示(也称为智能和哑)组件

在这里,您将获取数据并将其存储在容器组件中,然后通过@Input()将其传递给演示组件。您可以在此处销毁演示组件,而不必担心丢失状态。

  1. 路由器导航

最好使用路由器导航的概念来显示所需的容器组件,以不仅利用现有实践,而且让用户始终知道它们在应用程序中的位置。

  1. 最重要的一个-状态管理库-我使用NgRx,但听说过有关AkiraNGXS的好消息。

如果您从未使用过,则有一定的学习曲线 Redux模式,您可以将应用程序状态存储在一个地方,使其不可变,并从任何组件中引用它。