【问题标题】:Angular2 access a function/variable from another classAngular2从另一个类访问函数/变量
【发布时间】:2017-09-28 15:22:48
【问题描述】:

我想从父类访问子类的方法。

我的父类是

 export class Parent{
     constructor() {}
     present() {
     }
 }

我的孩子班是:

export class Child {
    constructor() {}
    submit(){  
        this.toast.present(); 
    }
}

我想在子类中从父类调用 present() 方法。

【问题讨论】:

  • 这些父类和子类在什么意义上?父母知道自己的孩子是谁吗?
  • 你检查过this link吗?
  • 根据您的代码,您希望从 Child 中的方法访问 parent 中的 present() 方法。是吗?并且,假设 ChildComponent 在您的示例视图中的 ParentComponent 中?
  • 是的@SaiyaffFarouk

标签: angular typescript ionic2 angular2-template angular2-directives


【解决方案1】:

您可以使用 @Output 装饰器发出事件。

您的子组件应该是:

import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child',
templateUrl: 'child.html',
})

export class Child {
@Output() notify: EventEmitter<string> = new EventEmitter<string>();

constructor() {}
submit(){  
    this.notify.emit();


  }
}

并且在父类模板中:

<child (notify)="toast.present();"></child >

【讨论】:

    【解决方案2】:

    你可以使用super关键字从Child调用Parent的方法

    class Parent{
         constructor() {}
         present() {
             console.log("I am from parent")
         }
    }
    
    class Child extends Parent{
         constructor() {
             super();
         }
    
        submit(){  
            super.present(); 
        }
    }
    
    let x = new Child();
    x.submit();
    

    【讨论】:

      【解决方案3】:
      1. 在 ECMA 6.0 中引入了 extends 关键字,其工作方式与 JAVA 完全相同。 该关键字用于通过创建可以访问父类的所有成员的子类来扩展类。

      2. 要访问 Parent 类的任何成员,我们使用“super”关键字。

        代码附在下面:

        类家长{ 构造函数() {

                 }
        
                 present() {
        
                 }
             }
        
        
                class Child extends Parent {
                  constructor() {
                    super();
                  }
        
                  submit(){  
                    super.present();   // here **super** represents an instance of Parent class
                  }
        
                }
        

      【讨论】:

        猜你喜欢
        • 2016-09-16
        • 2014-10-28
        • 1970-01-01
        • 2022-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多