Public or Private - Angular 2 class class method confusion

I am trying to understand which methods should be private and which should be publicly available in the component class.

It seems fairly easy to maintain to judge if the method is public or private, for example:

export class MyServiceClass { private _cache = {}; // this value is private and shouln't be accessed from outside public accessCache(){ // it public as it an API method return this._cache; } public setCache(newVal){ this._cache = newVal; } } 

Following this logic, all methods in the component must be private, because none of the methods should be displayed outside the class. (in accordance with this post, the component and its presentation are one entity)

 export class MyComponent { private _getRandomNumbers(){ // this is used in view only /*..*/ } } 

There is no tragedy, but then in this video you can find out that only public methods of the component tested should be used. Following the above, I cannot find reasons to have public methods in the component class, but I still have some methods worth checking out (especially the methods used). This means that I completely lost the meaning of private and public methods in the angular world.

So my question is simple:

which methods in the components should be marked as public and private.

+7
angularjs angular typescript
source share
1 answer

In the component class, I would say, set everything as public (if there is no access modifier, it is public by default).

In the normal case, we do not extend the class of components, so the access modifier is not needed, IMHO.

There are times when we inherit a component. See here component inheritance in Angular 2 . However, even in these cases, an access modifier may not be needed.

 ... export class MyComponent { // injected service as private constructor(private _randomSvc: RandomService) {} getRandomNumbers(){ } // leave it as public @Input() myInput: string; // leave it as public @Output() myOutput; // leave it as public } 

Remember that Javascript itself does not have an access modifier. The access modifier is applicable only during development (IDE). Although the modifier is useful in some cases, I would suggest minimizing its use.

+3
source share

All Articles