简体   繁体   English

Angular 8:使用同一服务的多个实例

[英]Angular 8: Using multiple instances of the same service

Does Angular 8 have an syntax change/upgrade for multiple instances of a service? Angular 8 是否对服务的多个实例进行了语法更改/升级? Doing this will not work below, as they are still sharing the same service data,这样做在下面不起作用,因为它们仍然共享相同的服务数据,

I Saw an answer here, just curious if Angular 8 providers for different syntax,我在这里看到了一个答案,只是好奇 Angular 是否有 8 个不同语法的提供程序,

Using multiple instances of the same service 使用同一服务的多个实例

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; 
         })

Product Service:产品服务:

export class ProductService{

  private messageSource = new Subject();
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(currentMessage) {
    this.messageSource.next(currentMessage);
  }
}

It is possible what you want, but not very descriptive though.这可能是您想要的,但描述性不是很强。 Better would be to just make ProductService abtract and extend from it with a CarService and FoodService , and use those as providers.更好的办法是使用CarServiceFoodService使ProductService抽象并从中扩展,并将它们用作提供者。

If you however want it like you ask for, I suppose you can do this:但是,如果您想要它,我想您可以这样做:

@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
  ) {}
}

Be aware though that any injected dependency provider from ProductService will be shared between these two.请注意,任何来自ProductService的注入依赖提供程序都将在这两者之间共享。 Which you can solve if necessary, by extending your factory如有必要,您可以通过扩展工厂来解决

If the ProductService does not inject any providers (which I doubt), you can just use new ProductService() in your component:如果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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM