如何导入提供的In:root单例服务



假设这是我的简单服务:

@Injectable({
providedIn: 'root'
})
export class UserpreferencesService {
color: string = 'yellow';
constructor() {
console.log("UserpreferencesService instance created");
}
}

我有两个组件,我想在其中使用来自服务的颜色字段。如果我在每个组件中导入服务,它就不会充当singleton:每次切换组件时,我都会有一个新的实例。这是斯塔克布利茨。

如果我不导入任何内容,服务将无法识别:"找不到名称UserpreferencesService"。这就是我如何使用组件内部的服务:

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-compone',
templateUrl: './compone.component.html',
styleUrls: ['./compone.component.css']
})
export class ComponeComponent implements OnInit {
constructor(private UserPreferences: UserpreferencesService) {
this.UserPreferences.color = 'green';
}
ngOnInit() {
}
}

该服务不在任何提供商列表中。我该如何解决这个问题?

每个组件中都必须有一个服务导入。我的问题是,我是从地址栏导航(这完全刷新了应用程序(。您必须使用routerLink才能获得单例服务。

最新更新