Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在引用中使用此构造函数,在角度中使用依赖项注入_Angular_Typescript_Dependency Injection_Constructor - Fatal编程技术网

Angular 在引用中使用此构造函数,在角度中使用依赖项注入

Angular 在引用中使用此构造函数,在角度中使用依赖项注入,angular,typescript,dependency-injection,constructor,Angular,Typescript,Dependency Injection,Constructor,我查看了Angular官方文档和其他博客,在构造函数中使用DI时看到了两种不同的语法,有时使用this,有时不使用this。哪一个是正确的 我知道我们需要在类的任何其他方法中使用this,但是为什么我们不在构造函数中使用this。或者只是private和public标识符就决定了这个 import { Component } from '@angular/core'; class NameService { getName () { return "Angular"; } }

我查看了Angular官方文档和其他博客,在构造函数中使用DI时看到了两种不同的语法,有时使用
this
,有时不使用
this
。哪一个是正确的

我知道我们需要在类的任何其他方法中使用
this
,但是为什么我们不在构造函数中使用
this
。或者只是
private
public
标识符就决定了
这个

import { Component } from '@angular/core';


class NameService {
  getName () {
    return "Angular";
  }
}

@Component({
  selector: 'my-app',
  template: '<h1>Favourite framework: {{ name }}</h1>'
})
class AppComponent {
  name: string;

  constructor(nameService: NameService) {
    this.name = nameService.getName(); // do not use this

  }

  otherMethod() {
    this.nameService.getName(); // use this
  }
}

那么我们什么时候用这个,什么时候不用?或者我们在后面的示例中使用此选项,因为它是关于Typescript的。在构造函数参数上使用
public
private
protected
时,如下所示

构造函数(私有记录器:记录器){}
实际上,Typescript创建了一个同名字段并为您设置它。 因此,您可以简单地编写上面的代码,而不是编写下面的代码

私有记录器:记录器;
构造函数(记录器:记录器){
this.logger=记录器;
}
由于您已经编写了
专用记录器
,因此只需将字段与
this
一起使用即可。在构造函数中如何使用它并不重要

有一个地方你可以尝试一下,看看自己。在左框中键入的任何内容都将在右框中转换为纯JS(ES5)

@Optional
decorator只是告诉Angular如果找不到要注入的对象就可以了

经验法则:

如果您在任何字段上使用
private
protected
public
,并希望使用它,请始终使用
(在构造函数内)

如果未使用上述任何关键字标记字段,则无法使用
this
,也无法在构造函数之外访问该对象


如果您需要访问类的属性/方法,您必须使用
this

感谢您的解释,但仍然不清楚是否在构造函数中使用
this
?但是默认关键字是
public
。不是吗?但它会在角度上抛出错误,并要求设置
私有
。顺便说一句,这个拇指规则只适用于构造函数体。该类的任何其他方法只能通过
this
访问服务。是吗?没有默认关键字。如果不显式定义,typescript将不会为您创建字段。此外,如果需要访问类的任何属性,则必须使用
this
。在构造函数中,您不需要使用
this
,因为它也是构造函数的一个参数。这很有意义。再次感谢你。
constructor(@Optional() private logger: Logger) {
  if (this.logger) {
    this.logger.log(some_message); // using this
  }
}