[英]Angular 8: Using multiple instances of the same service
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);
}
}
这可能是您想要的,但描述性不是很强。 更好的办法是使用CarService
和FoodService
使ProductService
抽象并从中扩展,并将它们用作提供者。
但是,如果您想要它,我想您可以这样做:
@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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.