Angular 6:在注入任何服务时使用访问修饰符 [英] Angular 6 : Use of access modifier while injection any service

查看:22
本文介绍了Angular 6:在注入任何服务时使用访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在您的组件中注入服务时,如果您错过了访问修饰符,它将给您如下所示的错误,但将其添加为私有或公共将运行良好.

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

导出类 UserDetailsComponent 实现 OnInit {名称="";姓氏="";构造函数(用户服务:用户服务服务){}ngOnInit() {}节省(){this.userService.saveUser();}}

<块引用>

UserDetailsComponent"类型上不存在属性userService".

解决方案

如果在构造函数参数前面加上访问修饰符(privateprotectedpublic) 或 readonly,它会自动被提升"为 TypeScript 中的类属性.这个构造被称为构造函数参数属性.

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

来自手册:

<块引用>

参数属性是通过在构造函数参数前加上前缀来声明的带有可访问性修饰符或 readonly,或两者.使用 private为参数属性声明并初始化一个私有成员;同样,publicprotectedreadonly 也是如此.

While going through the tutorial, i am coming across a strange scenario.

while injecting the service in your component if you miss the access modifier it will give you error as given below, but adding it as private or public will run fine.

Dont we have any default scope in Angular if we miss the access modifier ?

export class UserDetailsComponent implements OnInit {

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

  ngOnInit() {
  }

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

  }

}

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

解决方案

If you prefix a constructor parameter with an access modifier (private, protected or public) or readonly, it automatically gets "promoted" to be a class property in TypeScript. This construct is referred to as constructor parameter properties.

Without the prefix, the constructor parameter is nothing more than a method parameter, and you would have to manually assign it to a declared class property from the constructor itself.

From the handbook:

Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly, or both. Using private for a parameter property declares and initializes a private member; likewise, the same is done for public, protected, and readonly.

这篇关于Angular 6:在注入任何服务时使用访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆