在 Angular 2 中使用生命周期接口

Use Lifecycle Interface in Angular 2

这条规则到底有什么作用?

"use-life-cycle-interface": true,

这不是内置的 tslint 规则。这是由 codelyzer.

定义的规则

GitHub 存储库有一个视频(我没看过),但文档很少。幸运的是,作者已经实现了测试,所以可以推断出 use-life-cycle-interface rule does from its test descriptions:

it(`should fail, when a life cycle hook is used without implementing it's interface`, ...
it(`should fail, when life cycle hooks are used without implementing their interfaces`,  ...
it(`should fail, when some of the life cycle hooks are used without implementing their interfaces`, ...

它只是意味着你必须为你使用的每个生命周期钩子添加 implements 关键字,

虽然这对于 angular 识别和使用挂钩来说不是必需的,但对于代码清晰度和维护来说更好。

示例:

// don't forget the import
import { AfterViewInit } from '@angular/core';
// you have to have this implements statement 
export class YourComponent implements AfterViewInit {
  // if you want to use this hook
  ngAfterViewInit() {
    // your code...
  }
}