简体   繁体   中英

Typescript: How can I set an optional parameter if no value is passed in a derived class?

I have a base class:

export class ClientBase {

  constructor(private uri: string, private httpClient: HttpClient) { }

  // My Various Methods
}

I have several classes that derive from the ClientBase

For example:

@Injectable()
export class GizmoService extends ClientBase {

  constructor(private http: HttpClient)  
  {    
    super(environment.gizmoUri, http);
  }

};

So in the GizmoService I want to specifically pass the Uri in one particular case..

So ideally I would like to do something like this:

@Injectable()
export class GizmoService extends ClientBase {

  constructor(private http: HttpClient, uri?: string)  
  { 
    if (!uri) uri = environment.gizmoUri;
    super(uri, http);
  }

};

However I get error message that super must be the first call in the constructor.

How can I get around this without having to make massive changes to the existing code base? (ie Not changing every call to pass 2 parameters)

You could always give the uri parameter a default value.

@Injectable()
export class GizmoService extends ClientBase {

  constructor(private http: HttpClient, uri: string = environment.gizmoUri) { 
    super(uri, http);
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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