Global variable and injectable issue

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 ? :unamused:

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.