Typescript类的实现模式

时间:2019-04-26 19:40:13

标签: javascript typescript

我尝试更多地使用类,因此我为模型生成了interfaceclass

export interface IIndexClient {
  id?: number;
  name?: string;
  user_id?: number;
  location_id?: number;
  mindbody_id?: number;
  appointment_type?: string;
  found?: boolean;
  time?: string;
  status?: string;
  submitted?: boolean;
  consult_status?: boolean;
  consultation_id?: number;
  consultation?: IConsultation;
}

export class IndexClient implements IIndexClient {
  public id?: number;
  public name?: string;
  public user_id?: number;
  public location_id?: number;
  public mindbody_id?: number;
  public appointment_type?: string;
  public found?: boolean;
  public time?: string;
  public status?: string;
  public submitted?: boolean;
  public consult_status?: boolean;
  public consultation_id?: number;
  public consultation?: IConsultation;

  constructor( data: Partial<IIndexClient>,
               private locationService ) {
    Object.assign(this, data);
  }

  getLocationName() : string {
    return this.locationService.locations.filter((loc) => loc.id == this.location_id)[0].name
  }

我需要能够使用getLocationName()函数,但是它需要LocationService的实例才能访问locations。问题是,现在当我创建IndexClient的实例时,我需要包括LocationService

this.client = new IndexClient(this.client, this.locationService);

是否有某种方法可以访问我的IndexClient类中的提供程序的值,而不必每次都提供它?

1 个答案:

答案 0 :(得分:0)

这是一个有趣的解决方案。

https://nehalist.io/dependency-injection-in-typescript/

希望您也感兴趣。

致谢。