首页 > 解决方案 > 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);
  }
}

标签: javascripthtmlangularangular8

解决方案


这可能是您想要的,但描述性不是很强。更好的做法是使用 and 对其进行抽象ProductService和扩展,并将它们用作提供者。CarServiceFoodService

但是,如果您想要它,我想您可以这样做:

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

推荐阅读