簡體   English   中英

Angular 2提供了使用類,如何僅一次初始化父類

[英]Angular 2 provide with use class, how to init parent class only once

我有一個ParentService和它的幾個孩子。

@Injectable()
export class ParentService {
   car:Car;
   get Car():Car {
      return this.car;       
   }
   set Car(car:Car){
      this.car = car;
   }
   ...

}

@Injectable()
export class ChildService extends ParentService {
    constructor(...){
       super();
       ...
    }
}

@Injectable()
export class AnotherChildService extends ParentService {
        constructor(...){
           super();
           this.Car = new Car;
           this.Car.Year = 2015;
           ...
        }
    }

我擁有的第二件事是注入ParentService的服務。

@Injectable()
export class CarService{
    constructor(private serviceProvider:ParentService){
       this.car = this.serviceProvider.Car;
       ...
    }
}

在每個模塊中,我都“告知”該服務中要使用的子服務。 這是模塊示例之一:

@NgModule({
   ....
   providers: [
      {provide:ParentService, useClass:AnotherChildService},
      ....
   ]
})
export class AnotherChildModule{
    ...
}

問題是:我確實看到注入的服務是正確的。 但是,ParentService初始化了兩次(構造函數被調用了兩次),這使數據不是正確的數據。

例如,在下面的serviceProvider.Car中是未定義的,即使汽車是在AnotherChildService的構造函數中初始化的

@Injectable()
    export class CarService{
        constructor(private serviceProvider:ParentService){
           this.car = this.serviceProvider.Car;
           ...
        }
    }

我做錯什么了嗎? 有什么問題?

我找到了解決方案,我只需要使用useExisiting,而不是useClass。

{provide:ParentService, useExisting:AnotherChildService}

這里是參考: https : //angular.io/guide/dependency-injection-in-action

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM