Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular would it be ok/proper to have the constructor above class variables?

IE: instead of this:

export class MyComponent implements OnInit {
  users: User[];
  error_message: string;
  constructor(public authService: AuthService, public router: Router) { }

This (Looks cleaner and more proper to me)

export class MyComponent implements OnInit {
  constructor(public authService: AuthService, public router: Router) { }
  users: User[];
  error_message: string;

I couldn't find any documentation on this in the Angular style guide: https://angular.io/guide/lifecycle-hooks

like image 615
Leon Gaban Avatar asked Oct 22 '25 05:10

Leon Gaban


1 Answers

Is it okay? Sure it is okay. Is it proper - that is debatable. It certainly is not conventional.

What happens when you start needing to use your member variables in your constructor?

In this case: If you continue to declare your variables below your constructor, sure it will work, but it certainly isn't pleasant for readability. Alternatively in this case you could declare those member variables above your constructor, but then you will have inconsistencies in you files. (i.e. some files with member variables defined before the constructor and some defined after.)

I'd recommend sticking to the convention of defining all your member variables at the beginning of the class prior to the constructor, but hey that is just my two cents! :)

like image 145
Narm Avatar answered Oct 24 '25 19:10

Narm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!