angular2的继承

Shr*_*air 5 inheritance components typescript ecmascript-6 angular

我正在尝试了解angular 4中的继承。

以下是我的AppComponent文件:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'app';
  myArray= ["1","2","3"]; //THIS WORKS
  //myArray:any; //Declared but not initialized

  setTitle(value:any){
    this.title=value;
    console.log(this.myArray[2]);

  }
  ngOnInit(){
    //this.myArray=["1","2","3"]; //THIS DOESNT WORK

  }
}
Run Code Online (Sandbox Code Playgroud)

这是扩展AppComponent的另一个组件

import { Component, blurbs } from '@angular/core';
import { AppComponent } from '../app.component';

@Component({
  selector: 'app-child',
  templateUrl: `<p>
  title {{title}}
  <button (click)="setTitle('child')">change title</button>
</p>`,
  styleUrls: ['./child.component.css']
})

export class ChildComponent extends AppComponent implements OnInit {

  constructor() {
    super();
   }

  ngOnInit() {
  }

}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我从ChildComponent 调用setTitle()方法。

我有一个myArray [2]的控制台日志。

如果我在声明时初始化值,则该值工作正常。

但是,如果我只是在ngOnInit块中声明并初始化数组,则console.log 无法正常工作,并告诉我myArray [2]未定义。

我的应用程序中有一个类似的场景,有人可以指导我什么是正确的方法,以及当我在ngOnInit块中初始化数组时为什么它不起作用

Est*_*ask 7

ngOnInit方法在中重新定义ChildComponent,此行

   //this.myArray=["1","2","3"]; //THIS DOESNT WORK
Run Code Online (Sandbox Code Playgroud)

永远不会执行。

如果ChildComponent应该ngOnInit从父类继承方法,则不应定义自己的方法。如果应该扩展它,则应调用parent的方法:

  ngOnInit() {
    super.ngOnInit();
    ...
  }
Run Code Online (Sandbox Code Playgroud)