0

Consider this example

  export class A{
    b():void{}
    c():void{}
    }

And I am in Module M I want to use b() and C() within module M but I don't want to expose method b() to any other module but still give access to method c(). Is this possible in angular?

Liam
  • 27,717
  • 28
  • 128
  • 190
Darksilence
  • 159
  • 1
  • 10
  • 2
    put `private` in front of the method name – bherbruck Apr 18 '21 at 02:40
  • Does this answer your question? [Private "functions" in TypeScript](https://stackoverflow.com/questions/16919473/private-functions-in-typescript) – msanford Apr 18 '21 at 03:13
  • Adding private will make the method b() inaccessible even within the module M. So any component within the Module M will not have to b() too but that's not what I want. I want Module M to have full access to all the Class A methods within module 'M' – Darksilence Apr 18 '21 at 03:22
  • 1
    You should clarify a bit more your context. What does your class represent in your Angular app? A component? A service? When you say "I don't want to expose method b() to any other module" do you mean that b() should still be defined but as a private method or could not be defined at all? – lbsn Apr 18 '21 at 12:52
  • First things first, a module is not typescript. It's an angular concept. So your goal is to not expose this class outside of the module but you want it available inside the module? – Liam Apr 19 '21 at 09:01

1 Answers1

0

I'm assuming your class represents a service.

You can define a base class where you set the shared logic for your service and then extend that class with different implementations of the b() method. To avoid duplication of your b() logic, you can encapsulate that logic in a protected method on base class and let your public and private version of b() just call that method:

export class BaseService {
    protected _b() {
        return 'This string comes from b() method'
    }
    c() {
        return 'This string comes from c() method'
    }
}

@Injectable()
export class BaseServiceWithPublicB extends BaseService {
    b() {
        return super._b()
    }
}

@Injectable()
export class BaseServiceWithPrivateB extends BaseService{
    private b() {
        return super._b()
    }
}

Then you provide BaseServiceWithPublicB in module M, BaseServiceWithPrivateB in any other module:

@NgModule({
    declarations: [],
    providers: [{provide: BaseService, useClass: BaseServiceWithPublicB}],
    exports: []
})
export class ModuleWithPublicB { }

@NgModule({
    declarations: [],
    providers: [{provide: BaseService, useClass: BaseServiceWithPrivateB}],
    exports: []
})
export class ModuleWithPrivateB { }
lbsn
  • 2,322
  • 1
  • 11
  • 19