在Angular中创建服务的单个实例

时间:2019-05-29 14:30:42

标签: angular angular-services

演示的示例代码: 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;
  }

}

1 个答案:

答案 0 :(得分:-1)

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

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

相关问题