简体   繁体   English

如何导入提供的In: root singleton 服务?

[英]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.

相关问题 即使@Injectable 提供了provideIn: 'root',服务也会创建另一个实例。 如何确保服务是单身人士? - Service creates another instance even though @Injectable has providedIn: 'root'. How can I make sure the service is a Singleton? 使用与 providedIn 相同的服务:root 作为单例和组件的提供者与服务 - Using same service with providedIn: root as singleton and providers of component with the service 提供Angular 7服务:'root' - Angular 7 Service providedIn: 'root' 在“root”中提供的 angular 服务未定义 - providedin 'root' angular service is undefined 尽管使用了 @Injectable({providedIn: 'root' }) 装饰器,Angular 服务在注入到组件中时不会充当单例 - Angular Service not acting as singleton when injected in components despite using @Injectable({providedIn: 'root' }) decorator 如何使用 Angular 6/7 将服务注入另一个服务? (providedIn: 'root') 服务总是未定义的 - How to inject service into an another service with Angular 6/7 ? (providedIn: 'root') Service is always undefined Angular 提供的服务:'root' 为空 object - Angular service with providedIn: 'root' is an empty object 如何在 Angular 2 中创建单例服务? - How do I create a singleton service in Angular 2? 如何使用带角度5的@Injectable providedIn根获取 - How to use the @Injectable providedIn root in angular 5 with getting 角度服务装饰器提供了对延迟加载的根效果 - Angular service decorator providedIn root effect on lazy loading
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM