gpt4 book ai didi

Angular 6 : Use of access modifier while injection any service

转载 作者:太空狗 更新时间:2023-10-29 17:47:40 24 4
gpt4 key购买 nike

在学习本教程时,我遇到了一个奇怪的场景。

在你的组件中注入(inject)服务时,如果你错过了访问修饰符,它会给你如下所示的错误,但是将它添加为私有(private)或公共(public)将运行正常。

如果我们错过了访问修饰符,难道我们在 Angular 中没有任何默认范围吗?

export class UserDetailsComponent implements OnInit {

name="";
lastName="";
constructor(userService : UserServiceService) { }

ngOnInit() {
}

save(){
this.userService.saveUser();

}

}

Property 'userService' does not exist on type 'UserDetailsComponent'.

最佳答案

如果您在构造函数参数前加上访问修饰符(privateprotectedpublic)或readonly ,它会自动“提升”为 TypeScript 中的类属性。此构造称为构造函数参数属性

如果没有前缀,构造函数参数只不过是一个方法参数,您必须手动将其分配给构造函数本身声明的类属性。

来自handbook :

TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public, private, protected, or readonly. The resulting field gets those modifier(s):

关于 Angular 6 : Use of access modifier while injection any service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53075139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com