【问题标题】:Inheritance in angular2angular2中的继承
【发布时间】:2018-06-03 21:21:46
【问题描述】:

我正在尝试理解 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 块中初始化数组时它不起作用

【问题讨论】:

    标签: angular typescript inheritance ecmascript-6 components


    【解决方案1】:

    ngOnInit方法被重新定义在ChildComponent,这一行

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

    永远不会被执行。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-09
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      相关资源
      最近更新 更多