2

I was reading some code written several months ago by another fellow and I found this declaration/assignation in ngOnInit function, from a service that is being injected on the constructor.

constructor(private _authService: AuthService) { } 

ngOnInit() {
 const { _authService } = this; 
}

What's the point of using const and assigning to the service that is being injected the this keyword? I wasn't able to find any similar question. I also looked at the TypeScript documentation without finding anything useful.

1
  • 3
    I guess whoever wrote that didn't want to write this._authService, although I couldn't tell you why. It's not really TypeScript- or Angular-related, just general JS destructuring. Commented Aug 21, 2020 at 10:52

1 Answer 1

2

When we declare the variable in constructor. It is mounted on the this object. So that means if you have to use it in the component. You will use it like.

this._authService.xyz();

But you can also destructure values from this object. So doing

const { _authService } = this; 

Just allows us to use _authService directly as a variable.

Sign up to request clarification or add additional context in comments.

3 Comments

but.... why not declare the service as public? constructor(public _authService: AuthService) { }
It is just for encapsulation. When we say the variable is private. It means we don't want it to be used outside of this class. And public variables can be accessed from the outside.
But typescript only enforces this on compile time. As javascript itself does not have private or public.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.