Theme switcher on localstorage observable service

时间:2019-01-09 21:44:25

标签: javascript angular angular-material local-storage observable

I implemented a dynamic theme switcher (with tutorial) in my angular app. It work's but when I reload website, the choice is not remembered.

I read about localStorage and i will use it but still doesn't work because I don't know how "where" I should get data from this localStorage, that the choice of the theme will be remembered when I reload the page.

I have this code:

theme.service.ts new version

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';


@Injectable()
export class ThemeService {
  private _themeDark: Subject<boolean> = new Subject<boolean>();

  isDarkFunction() {
let value = localStorage.getItem('isDark');
this._themeDark.next(value);
return this._themeDark.asObservable();
  }

  isThemeDark = this.isDarkFunction();

  setDarkTheme(isThemeDark: boolean) {
    this._themeDark.next(isThemeDark);
    localStorage.setItem('isDark', JSON.stringify(isThemeDark));
  }

}

navbar.component.html

<div class="container-fluid switcher-container">
    <mat-slide-toggle [checked]="isThemeDark | async" (change)="toggleDarkTheme($event.checked)">Dark theme</mat-slide-toggle> 
</div>

navbar.component.ts

import { Component, OnInit } from '@angular/core';
import { ThemeService } from '../services/theme.service'; 
 import { Observable } from 'rxjs/Observable'; 

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {

  isThemeDark: Observable<boolean>; 

  constructor(
    private themeService: ThemeService) { }

  ngOnInit() {
    this.isThemeDark = this.themeService.isThemeDark; 
  }

  toggleDarkTheme(checked: boolean) { 
    this.themeService.setDarkTheme(checked); 
  } 

}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs/Observable"; 
import { ThemeService } from "./services/theme.service"; 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [ThemeService]
})
export class AppComponent implements OnInit {

  isThemeDark: Observable<boolean>; 


  constructor(
    public themeService: ThemeService) {

    }

  ngOnInit() {
  this.isThemeDark = this.themeService.isThemeDark;

  }

}

Please help, Regards

2 个答案:

答案 0 :(得分:1)

您可以在 theme.service.ts 中编写如下内容。
我不知道它是否可以正常运行,但其想法是从isThemeDark()中的 localstorage 中读取。

isThemeDark() {
    let value = localStorage.getItem('isDark');
    this._themeDark.next(value);
    return this._themeDark.asObservable();
}

答案 1 :(得分:0)

我认为这是因为您在执行localStorage.getItem('isDark')时结果是字符串,而不是布尔值。也许尝试:

let value = JSON.parse(localStorage.getItem('isDark')) === true;

还可以手动检查刷新后是否保留了本地存储。某些浏览器具有一项设置,可以在刷新时清除所有内容。