javascript - Angular 8:使用同一服务的多个实例
问题描述
Angular 8 是否对服务的多个实例进行了语法更改/升级?这样做在下面不起作用,因为它们仍然共享相同的服务数据,
我在这里看到了一个答案,只是好奇 Angular 8 提供者是否提供不同的语法,
export class ProductComponent implements OnInit {
@Input() propertyViewDto: PropertyViewDto2;
carMessage: any;
foodMessage: any;
public carData: arcData;
public foodData: FoodData;
constructor
(
private readonly carService: ProductService,
private readonly foodService: ProductService..
ngOnInit() {
this.carService.currentMessage.subscribe(currentMessage => {
this.carMessage = currentMessage;
this.carData= this.carMessage.value;
})
this.foodService.currentMessage.subscribe(currentMessage => {
this.foodMessage = currentMessage;
this.foodData= this.foodMessage.value;
})
产品服务:
export class ProductService{
private messageSource = new Subject();
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(currentMessage) {
this.messageSource.next(currentMessage);
}
}
解决方案
这可能是您想要的,但描述性不是很强。更好的做法是使用 and 对其进行抽象ProductService
和扩展,并将它们用作提供者。CarService
FoodService
但是,如果您想要它,我想您可以这样做:
@Component({
//...
providers: [
{ provide: 'carService', useFactory: (/*deps*/) => new ProductService(), deps: [] },
{ provide: 'foodService', useFactory: (/*deps*/) => new ProductService(), deps: [] }
]
})
export class ProductComponent {
constructor(
@Inject('carService') private readonly carService: ProductService,
@Inject('foodService') private readonly foodService: ProductService
) {}
}
请注意,任何注入的依赖提供者ProductService
都将在这两者之间共享。如有必要,您可以通过扩展工厂来解决
如果ProductService
没有注入任何提供程序(我怀疑),您可以new ProductService()
在您的组件中使用:
@Component({
//...
providers: []
})
export class ProductComponent implements OnInit {
private readonly carService = new ProductService();
private readonly foodService = new ProductService();
}
推荐阅读
- reactjs - 如何在 React 中对元素的子项进行字体保护
- c - 是否可以在C中使用for循环来确定用户输入的值中哪个值最小而不使用数组?
- python - 将 cookie 导入 Selenium 不起作用
- node.js - 快递应用程序未向 MongoDB 发送 POST 请求
- cortex-m - 关于Cortex-M3向量表放置的问题
- node.js - 如何从 jwks-rsa 的 getSigningKey 函数中获取公钥
- mysql - Delphi Unidac MySQL 从备忘录代码语法错误创建触发器
- python - 执行带参数的python脚本
- node.js - 虚拟机中的 NPM 安装问题
- javascript - @HostListener 用于自动填充 Angular 中的输入字段