我如何导入ProvidedIn:根单例服务?

问题描述 投票:0回答:1

让我们说这是我的简单服务:

 @Injectable({
      providedIn: 'root'
    })
    export class UserpreferencesService {
      color: string = 'yellow';

      constructor() {
        console.log("UserpreferencesService instance created");
     }
    }

我有两个要在服务中使用颜色字段的组件。如果我在每个组件中导入服务,则该服务将不会充当单例:每次切换组件时,我都会有一个新实例。这是Stackblitz

如果我不导入任何内容,将无法识别该服务:“找不到名称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() {
  }
}

该服务不属于任何提供商列表。我该如何解决?

angular singleton
1个回答
0
投票

每个组件中的服务都必须导入。我的问题是我正在从地址栏导航(此完整刷新了应用程序)。您必须使用routerLink来获得单例服务。

© www.soinside.com 2019 - 2024. All rights reserved.