会话存储 Angular 4/5

Session Storage Angular 4/5

本项目如何实现Session存储?: https://stackblitz.com/edit/dynamic-material-theming

当我选择浅色并关闭浏览器并 return 时 - 我希望保留浅色

我会使用 LocalStorage。这是关于它的文档的 link。 https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

它没有提到的一件事是,如果 browser 不支持它,您将 运行 遇到问题。因此,请确保您也能处理好这种情况。

import { Component, HostBinding } from '@angular/core';
import { OverlayContainer} from '@angular/cdk/overlay';

const THEME_LOCAL_STORAGE_KEY = 'selectedTheme';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  name = 'Angular 5';
  @HostBinding('class') componentCssClass;

  constructor(public overlayContainer: OverlayContainer){
    const theme = localStorage.getItem(THEME_LOCAL_STORAGE_KEY);      

    if(theme){
      this.onSetTheme(theme);
    }    
  }


  onSetTheme(theme) {
      this.overlayContainer.getContainerElement().classList.add(theme);
      this.componentCssClass = theme;
      localStorage.setItem(THEME_LOCAL_STORAGE_KEY, theme);      
  }
}