網站搜尋

angular - 在 angular2 中的繼承


我正在嘗試理解 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

  }
}

這是另一個擴展 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() {
  }

}

在上述程式碼中,我正在從 ChildComponent 呼叫 setTitle() 方法。

我有一個 myArray[2] 的控制台日誌。

如果我在宣告變數的同時初始化它,這個值就能正常運作。

但是如果我只在 ngOnInit 區塊中宣告並初始化陣列,console.log 就無法運作,並且告訴我 myArray[2] 是未定義的。

我在應用程式中有類似的情況,有人可以指導我正確的方法是什麼,以及為什麼當我在 ngOnInit 區塊中初始化陣列時它不會工作嗎

答案#1

ngOnInit 方法在 ChildComponent 中被重新定義,這一行

   //this.myArray=["1","2","3"]; //THIS DOESNT WORK

從未執行。

如果 ChildComponent 應該從父類別繼承 ngOnInit 方法,它不應該定義自己的方法。如果它應該擴展該方法,則應該呼叫父類別的方法:

  ngOnInit() {
    super.ngOnInit();
    ...
  }