[英]Create Single Instance of Service in Angular
sample code for demo: https://stackblitz.com/edit/angular-9zjkyf 演示的示例代码: https : //stackblitz.com/edit/angular-9zjkyf
I need a global shared service that can be accessed from any part of the app, I have been following along the documentation: 我需要一个可以从应用程序的任何部分访问的全局共享服务,我一直在遵循文档:
https://angular.io/guide/singleton-services https://angular.io/guide/singleton-services
I have setup a sample service that generates a random number and when used in modules I would expect any component calling the service to get the same number, but they are different, which makes me think that there are multiple instances of my service 我已经设置了一个生成随机数的示例服务,并且在模块中使用该服务时,我希望任何调用该服务的组件都能获得相同的数字,但是它们是不同的,这使我认为我的服务有多个实例
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 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 is right. @ Jota.Teledo是正确的。 Don't put the service in the Providers array.
不要将服务放在Providers数组中。 Putting it there creates a new instance at the component level.
将其放在此处会在组件级别创建一个新实例。
Just put it in the constructor and the DI will grab the root, singleton instance. 只需将其放入构造函数中,DI即可获取根单例实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.