1

I’m having type script class which expose some service list

I’ve defined a property that should have reference to the ServiceCatalog class like following:

export default class myGenerator extends Generator {

  private svcat: ServiceCatalog | undefined;


  // and here I’ve initilzied the property 

 await this.getSvc();

// here I created some function the return service instances
private async getSvc() {
  this.svcat = new ServiceCatalog();
  await this.svcat.getServiceInstances();
}


// and here I’ve additional code which use it 

this.svcat.values  ….

My question is there Is a better/cleaner way of doing the in javascript/typescript ? maybe not using the this keyword...

And also maybe a better code for testing (unit-test) ...

3
  • Sorry, the question is not clear to me. You are trying to initialise the svCat and run the getServiceInstances? Can you paste the whole code of your class? Right now, this is not a valid Typescript class. Commented Sep 16, 2020 at 10:08
  • @Guilhermevrs - yes this is what im trying to do, the class is a lot longer... what is not valid ? this.svcat.values …. i put it just an example for usage ... Commented Sep 16, 2020 at 10:13
  • @Guilhermevrs - what Im doing is calling to the class (serviceCatalog) and keep the object inside myGenerator class Commented Sep 16, 2020 at 10:14

2 Answers 2

1

The way you are doing today, it is very hard to test. Why is that? Well, because if you want to isolate your Generator class from your ServiceCatalog, you will have a hard time.

What I suggest, like the colleague above, is to have the ServiceCatalog coming by customer BUT have a default value.

class MyGenerator extends Generator {
  constructor(private svCat: ServiceCatalog = new ServiceCatalog()) {
      super();
  }
}

This way you can use it normally like

new MyGenerator()

or for testing

new MyGenerator(myFakeServiceCatalog)
Sign up to request clarification or add additional context in comments.

Comments

1

Inject the Service into your myGenerator class. Add this to your constructor:

    constructor(private svcat:ServiceCatalog) {}

You can now access the injected Service using

    await this.svcat.getServiceInstances();

There is no need to add a property (your svcat:ServiceCatalog|undefined part) for the service.

"this" is needed a lot in java/type-script since it refers to the current class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.