Angular 2 component class methods confusion

I struggle to understand which methods should be private and which should be public in component class.

It seems to be fairly easy in service to judge if method is public or private eg:

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

Following that logic all methods in component should be private because none of the methods should be exposed outside of the class. (according to to that post component and its view 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 learn that only public methods of component should be unit tested. By following above I can't find any reason to have public methods in component class but I still have some methods which are worth testing (especially methods used in view). It means that I'm completely lost in the meaning of private and public methods in angular world.

So my question is simple:

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


In Component Class, I would say, set everything as public (if no access modifier, it's public by default).

In normal case, we don't extends a component class, therefore, access modifier is not needed, IMHO.

There are cases where we will inherit a component. See here component inheritance in Angular 2. However, even in these cases, access modifier might not be necessary.

...

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 Javascript itself has NO access modifier. The access modifier only applicable during development(IDE). While modifier is useful in some cases, I would suggest minimise the usage of that.

链接地址: http://www.djcxy.com/p/92344.html

上一篇: 带缩放类型centerCrop过渡的共享元素会跳动

下一篇: Angular 2组件类方法混淆