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

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

问题描述

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

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.

如果我们缺少访问修饰符,我们在Angular中是否没有任何默认范围?

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();

  }

}

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

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

推荐答案

如果在构造函数参数前添加访问修饰符(privateprotectedpublic)或readonly,它将自动获得升级" "作为TypeScript中的类属性.这种构造称为构造器参数属性.

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.

来自手册:

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

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.

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

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