Hi !
I have a question about global variables, I saw I could do something like this :
@Injectable()
export class idUser {
constructor() {
this.idUser = "4";
}
setIdUser(value) {
this.idUser = value;
}
getIdUser() {
return this.idUser;
}
}
But I actually donât works for me, I have this issue :
Property âidUserâ does not exist on type âidUserâ.
Do you know why ? 
Thanks !
Yes, because you have never declared an idUser
property. Please follow JavaScript naming conventions: camelCase for properties, PascalCase for classes, leading underscore for privacy:
export class UserIdHolder {
private _userId = "4";
getUserId(): string {
return this._userId;
}
setUserId(uid: string): void {
this._userId = uid;
}
}
1 Like
Okay so the tutorial Iâve been following is badâŚ
But okay, I understand how to declare it now, but what is the syntax to use it then in the code ?
I mean if I want to send my user id via a http request, how can I get the value ? itâs UserIdHolder.getUserId() ?
Thanks a lot rapropos
Thatâs a bit of a religious argument.
Yes, that is correct given what weâve talked about so far.
The only reason I can think of to make the property private and only allow access via getters/setters is for encapsulation purposes (i.e. you can set breakpoints on the setter to figure out where it is changed). JavaScript has such pathetic language support for encapsulation that I have come to the conclusion that there isnât much merit in this, and you might as well just make userId
a publicly accessible property and forgo the getters and setters. This isnât a strongly-held opinion, and if you want to stick with the getters and setters, I think that is a perfectly defensible design decision.
Code clarity might be another argument for getters/setters. Especially if you come from a lang where they are common.
I guess thatâs an âeye of the beholderâ topic. I find getters/setters that do nothing but get and set a meaningless nuisance generally.
One thing I feel more strongly about is the notion of surreptitious get/set functions that JavaScript allows. I find them confusing and best avoided. If we are going to allow access to a member, do so. If we are going to mandate that it must go through getter/setter functions, fine. But that âoh, weâre assigning to it but it really goes through a functionâ I do not like.