[英]How do I import the providedIn: root singleton service?
Let's say this is my simple service:假设这是我的简单服务:
@Injectable({
providedIn: 'root'
})
export class UserpreferencesService {
color: string = 'yellow';
constructor() {
console.log("UserpreferencesService instance created");
}
}
I have two components where I want to use the color field from the service.我有两个组件,我想在其中使用服务中的颜色字段。 If I import in each component the service it won't act as singleton: I'll have a new instance every time I switch components.如果我在每个组件中导入服务,它将不会充当 singleton:每次切换组件时都会有一个新实例。 Here is the Stackblitz .这是Stackblitz 。
If I don't import anything the service won't be recognized: "Cannot find name UserpreferencesService".如果我不导入任何内容,则无法识别该服务:“找不到名称 UserpreferencesService”。 This is how I use the service inside component:这就是我在组件内部使用服务的方式:
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() {
}
}
The service is not part of any providers list.该服务不属于任何提供商列表。 How can I solve this?我该如何解决这个问题?
There must be an import for the service in each component.每个组件中必须有服务的导入。 My problem was that I was navigating from the address bar (this full refreshes the app).我的问题是我从地址栏导航(这完全刷新了应用程序)。 You have to use routerLink to have singleton service.您必须使用 routerLink 才能获得 singleton 服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.