Angular 18 同一服务的多个实例

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

我已经:

服务DataLoader,在数据库中读取/写入数据。

服务报告谁使用注入实例 DataLoader

也注入 DataLoader 和 Report 的独立组件。

此时,只有一个 DataLoader 实例正在运行,并且我需要内部 Report,DataLoader 的独占实例,我的冲突是因为当组件尝试使用某些功能时,内部的值仍然来自上次使用(Report),我需要保留组件实例中的值。

在恢复中,我认为我需要 DataLoader 的多个实例,并以某种方式注入其他服务中

angular dependency-injection inject angular-dependency-injection angular-injector
1个回答
0
投票

在你的组件装饰器中

@Component({
selector: 'my-component',
providers: [MyService], <--- here add your service 
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
})

为装饰器的提供者属性中的每个声明创建一个服务实例,如果提供,它将在根中创建的实例上使用。

如果您只想拥有独占实例并且不想在服务装饰器中拥有根实例:

@Injectable({
providedIn: 'root',
})

删除

{
    providedIn: 'root',
}

仅此而已

@Injectable()

依然存在。请记住,如果您这样做。您需要将其添加到组件或父组件的提供者数组中才能使其正常工作,否则您将得到

NullInjectorError

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