在提供服务的模块中添加一个静态变量,它将跟踪服务是否已初始化,并根据该状态来提供服务。具体实现如下:
// example.service.ts import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root', }) export class ExampleService { private static initialized = false;
constructor() { if (!ExampleService.initialized) { ExampleService.initialized = true; console.log('ExampleService initialized!'); } }
// Service logic...
}
使用该服务的组件或模块将在第一次使用该服务时将其初始化,因此服务将提供单例实例并且不会在其他模块中重新实例化。
// app.component.ts import { Component } from '@angular/core'; import { ExampleService } from './example.service';
@Component({ selector: 'app-root', template: '
这将确保ExampleService只会在第一次使用时进行初始化,并且它的单例实例将在应用程序的生命周期内保持不变。