简体   繁体   English

TypeScript const 声明变量

[英]TypeScript const declaration variable

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.我正在阅读几个月前由另一个人编写的一些代码,我在 ngOnInit function 中找到了这个声明/分配,来自在构造函数上注入的服务。

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?使用const并将this关键字分配给正在注入的服务有什么意义? I wasn't able to find any similar question.我找不到任何类似的问题。 I also looked at the TypeScript documentation without finding anything useful.我还查看了TypeScript 文档,但没有找到任何有用的信息。

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.它安装在这个 object 上。这意味着如果您必须在组件中使用它。 You will use it like.你会像使用它一样。

this._authService.xyz();

But you can also destructure values from this object. So doing但是你也可以从this object 中解构值。这样做

const { _authService } = this; 

Just allows us to use _authService directly as a variable.只是允许我们直接使用 _authService 作为变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM