src/app/services/app-settings.service.ts

Index

Properties
Methods

Constructor

constructor()

Properties

Public defaultSettings
Type : AppSettings
Default value : { persistSelectedTheme: true, selectedTheme: AppThemes.light }
Public settings
Type : unknown
Default value : new BehaviorSubject<AppSettings>(this.defaultSettings)

Methods

restoreAppSettings
restoreAppSettings()

Restore app settings from the local storage

Returns : void
setAppSettings
setAppSettings(appSettings: Partial<AppSettings>)

Function used in the app to update global settings object

Parameters :
Name Type Optional Description
appSettings Partial<AppSettings> No

contains properties that should be updated in settings

Returns : void
storeAppSettings
storeAppSettings()

Save app settings to the local storage

Returns : void
import { BehaviorSubject } from 'rxjs'
import { AppSettings, AppThemes } from '../models/AppSettings'

export class AppSettingsService {
  public defaultSettings: AppSettings = {
    persistSelectedTheme: true,
    selectedTheme: AppThemes.light
  }
  public settings = new BehaviorSubject<AppSettings>(this.defaultSettings)

  constructor() {
    this.restoreAppSettings()
  }

  /**
   * Restore app settings from the local storage
   */
  restoreAppSettings() {
    try {
      const serializedSettings = localStorage.getItem('app-settings')

      if (serializedSettings) {
        const settings = JSON.parse(serializedSettings)

        this.setAppSettings(settings)
      } else {
        console.info(
          'No app settings stored in the localStorage, we will set to default values.'
        )
      }
    } catch (err) {
      console.warn('Error restoring settings from local storgae.', err)
    }
  }

  /**
   * Save app settings to the local storage
   */
  storeAppSettings() {
    localStorage.setItem('app-settings', JSON.stringify(this.settings.value))
  }

  /**
   * Function used in the app to update global settings object
   *
   * @param appSettings contains properties that should be updated in settings
   */
  setAppSettings(appSettings: Partial<AppSettings>) {
    this.settings.next({
      ...this.settings.value,
      ...appSettings
    })

    this.storeAppSettings()
  }
}

results matching ""

    No results matching ""