要实现“本地存储可观察服务上的主题切换器”,可以按照以下步骤进行解决:
ThemeService
的服务类,用于管理主题切换的状态和逻辑。在该服务类中,需要引入rxjs
库的BehaviorSubject
类来创建可观察的主题状态。import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
private themeSubject: BehaviorSubject = new BehaviorSubject('light');
public theme$ = this.themeSubject.asObservable();
constructor() {}
// 切换主题
public toggleTheme() {
const currentTheme = this.themeSubject.getValue();
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
this.themeSubject.next(newTheme);
// 可以在这里存储新的主题到本地存储
}
}
ThemeService
,并在模板中使用theme$
可观察对象来动态显示主题。import { Component } from '@angular/core';
import { ThemeService } from './theme.service';
@Component({
selector: 'app-root',
template: `
`,
styles: [
`
.light-theme {
background-color: white;
color: black;
}
.dark-theme {
background-color: black;
color: white;
}
`
]
})
export class AppComponent {
theme$ = this.themeService.theme$;
constructor(private themeService: ThemeService) {}
toggleTheme() {
this.themeService.toggleTheme();
}
}
localStorage
或sessionStorage
来保存当前主题。// 在 ThemeService 中的 toggleTheme() 方法中添加以下代码
// 存储新的主题到本地存储
localStorage.setItem('theme', newTheme);
// 在 AppComponent 的构造函数中添加以下代码
// 恢复之前保存的主题
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
this.themeService.setTheme(savedTheme);
}
这样,当用户切换主题时,主题状态会通过可观察对象在应用中传播,同时会将新的主题保存到本地存储中,以便在下次加载应用时恢复之前的主题设置。