TypeScript const declaration variable

Viewed 124

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 Answers

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.

Related