为什么Angular的依赖注入需要私有或公共才能工作?

Lau*_*cia 3 scope dependency-injection typescript angular-services angular

我注意到,如果没有使用显式范围定义注入,角度类将无法识别注入的服务。

下面的代码不起作用

constructor(router: Router) {}
Run Code Online (Sandbox Code Playgroud)

但这个确实如此。

constructor(private router: Router) {}
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么?我相信,如果您没有显式编写属性的范围定义,那么默认情况下它是公共的,就像类属性一样,但似乎不是这里的情况。

Pie*_*Duc 7

无论您在构造函数中定义什么,都将作为参数。TypeScript您可以将访问器附加到其上,这很方便。例如:

constructor(private router: Router) {}
Run Code Online (Sandbox Code Playgroud)

是 ES6 的简写:

constructor(router) {
  this.router = router;
}
Run Code Online (Sandbox Code Playgroud)

如果您执行以下操作,依赖注入仍然有效:

constructor(router: Router) {
  // router only available in this scope
}
Run Code Online (Sandbox Code Playgroud)

只是它仅在构造函数内部可用,而不在类实例中可用,因为它位于构造函数{}范围内。类字段在类作用域中定义{},因此可以在整个类中访问