简体   繁体   English

为什么Angular中的ngOnInit不是私有的?

[英]Why is not ngOnInit in Angular private?

I'm checking the code samples and even the docs getting nothing av information. 我正在检查代码示例,甚至文档都没有得到任何信息。 Then, I google for a while and still nothing. 然后,我谷歌一段时间,仍然没有。

Why do we type 我们为什么打字

ngOnInit() { ... }

instead of 代替

private ngOnInit() { ... }

or, for that matter, as long as I'm whining on the subject 或者,就此而言,只要我抱怨这个话题

private ngOnInit() : void { ... }

to embrace the full power of TypeScript? 拥抱TypeScript的全部力量?

edit 编辑

Based on the comments I need to extend the question. 根据评论我需要扩展问题。 Why don't we write: 我们为什么不写:

public ngOnInit() : void { ... }

instead? 代替?

Based on the comments I need to extend the question. 根据评论我需要扩展问题。 Why don't we write: public ngOnInit() : void { ... } instead? 我们为什么不写: public ngOnInit() : void { ... }而不是?

TypeScript is able to provide contextual type information, so when you are implementing an interface, you don't need to repeat types from the interface. TypeScript能够提供上下文类型信息,因此在实现接口时,不需要从接口重复类型。

For example, if you consider the following shortened example: 例如,如果您考虑以下缩短的示例:

interface OnInit { 
  ngOnInit(): void
}

const example: OnInit = {
   ngOnInit: function () { }   
}

If you hover over ngOnInit you'll see the return type is already void, because it has inferred the return type for you contextually. 如果将鼠标悬停在ngOnInit您将看到返回类型已经无效,因为它已根据情况为您推断出返回类型。

上下文类型推断

So in short, TypeScript wants to save you having to repeat unnecessary annotations. 简而言之,TypeScript希望避免重复不必要的注释。

Return Type Compatibility 返回类型兼容性

There is one case that might make you consider adding the return type annotation. 有一种情况可能会让您考虑添加返回类型注释。 With no annotation, the following is allowed: 如果没有注释,则允许以下内容:

const x: OnInit = {
    ngOnInit: function () {
        return 4;
    }   
}

In the specific case of the OnInit interface, this won't cause any problems as the return type is ignored. OnInit接口的特定情况下,这不会导致任何问题,因为忽略了返回类型。 However, if you wanted to be told that your return type doesn't look right, the annotation would give you that additional information: 但是,如果您希望被告知您的返回类型看起来不正确,那么注释会为您提供其他信息:

interface OnInit { 
  ngOnInit(): void
}

const x: OnInit = {
    ngOnInit: function (): void {
        return 4;
    }   
}

Like this: 像这样:

返回类型检查

The method is called from Angular. 该方法是从Angular调用的。 If it were private, it couldn't be called from outside. 如果它是私人的,则无法从外部调用。

The returned value is ignored by Angular, therefore the return type doesn't matter. Angular会忽略返回的值,因此返回类型无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM