2017-06-14 44 views
0

我有一个ParentService和它的几个孩子。Angular 2提供了使用类,如何初始化父类只有一次

@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被初始化了两次(构造函数被调用两次),这使得数据不是正确的。

E.g.在下面的serviceProvider.Car是不确定的,即使汽车在行驶中的AnotherChildService

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

构造函数初始化难道我doind什么了吗?有什么问题?

回答