我想使用服务在我的所有组件(不一定相关)之间共享一个值。
网上有很多例子,但对我不起作用,我不知道我做错了什么。
此外,许多示例都是基于旧版本的 Angular,而我想使用现代方法来实现。
目前我有这 3 个文件,我想分享一个“主题”值:
主题.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
private _theme: 'light'|'dark' = 'light';
public get Theme() {
return this._theme;
}
public set Theme(theme: 'light'|'dark') {
this._theme = theme;
}
constructor() { }
}
app.component.ts:
import { Component, AfterViewInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ThemeService } from './services/theme.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
providers: [ThemeService],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent implements AfterViewInit {
constructor(private themeService: ThemeService) { }
ngAfterViewInit() {
console.log("app.component:", this.themeService.Theme);
this.themeService.Theme = "dark";
console.log("app.component:", this.themeService.Theme);
}
}
我的组件.组件.ts:
import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { ThemeService } from '../../services/theme.service';
@Component({
selector: 'app-mycomponent',
standalone: true,
imports: [],
providers: [ThemeService],
templateUrl: './mycomponent.component.html',
styleUrl: './mycomponent.component.scss'
})
export class MyComponent implements AfterViewInit {
constructor(private themeService: ThemeService) { }
ngAfterViewInit() {
console.log("mycomponent.component:", this.themeService.Theme);
}
}
我想要这样的结果:
app.component: light
app.component: dark
mycomponent.component: dark
但是我有这个:
app.component: light
app.component: dark
mycomponent.component: light
我想象这两个组件正在使用服务的不同实例,我该如何使服务在两者之间共享?
请勿将
ThemeService
添加到组件的 providers
数组中。该服务已经是providedIn: 'root'
,这意味着您已经拥有该应用程序的单例。如果您将服务添加到组件的 providers
数组中,您将创建只有该组件知道的第二个副本。