在 Angular 中创建单个服务实例

Create Single Instance of Service in Angular

演示示例代码: https://stackblitz.com/edit/angular-9zjkyf

我需要一个可以从应用程序的任何部分访问的全局共享服务,我一直在关注文档:

https://angular.io/guide/singleton-services

我已经设置了一个生成随机数的示例服务,当在模块中使用时,我希望调用该服务的任何组件都获得相同的数字,但它们是不同的,这让我认为有多个实例我的服务

service.ts

import { Injectable,OnInit } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService implements OnInit {

 random :number;

  constructor() {
    this.random = Math.random( );
   }
  ngOnInit() {

  }
}

component.ts

import { Component, OnInit } from '@angular/core';

import { UserService } from './user.service';
import { UserModule} from './user.module';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [UserService]
})
export class AppComponent implements OnInit {
  title = 'Users list';
  users: User[];
  rand: number;

  constructor(private userService: UserService) { }

  ngOnInit(): void {

    this.rand = this.userService.random;
  }

}

@Jota.Teledo 是对的。不要将服务放在 Providers 数组中。将它放在那里会在组件级别创建一个新实例。

只需将它放在构造函数中,DI 就会获取根、单例实例。