2017-05-25 36 views
0

我看到一個奇怪的錯誤,我嘗試從另一個方法調用方法,並且這兩個方法都在同一個Angular 2 TypeScript組件中。如何從同一個Angular(Typescript)組件類中的另一個方法調用一個方法?

在下面的代碼中看到,當調用ngOnInit()時,它將啓動method1。方法1試圖調用this.method2()。這是問題所在。 出現的錯誤如下: 錯誤:無法讀取未定義的屬性'method2'

爲什麼此對象未定義?我怎樣才能解決這個問題,以便我可以用像Java這樣的語言在同一個類中調用屬於某個類的方法?

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

@Component({ 
    selector: 'my-dashboard', 
    moduleId: module.id, 
    templateUrl: './dashboard.component.html', 
    styleUrls: [ './dashboard.component.css' ] 
}) 
export class DashboardComponent implements OnInit { 

    constructor() { 
    } 

    ngOnInit(): void { 
    this.method1(); 
    }; 

    method1(): void { 
    this.method2(); 
    }; 

    method2(]): void { 
    console.log("hi"); 
    } 
} 
+1

是的]一個錯字?在method2定義 –

+0

是的,應該工作,否則。我能看到的代碼沒有錯。 – pixelbits

回答

-1

這不是可運行的,所以我不能對此進行測試自己的解決方案,但嘗試重命名功能「this.method2」,而不僅僅是「方法2」。

0

我複製了你的確切代碼在這個Plunker(但從method2的參數中刪除了不常見的']'),它工作正常。我也添加了一個按鈕,以便多次調用Method1()。

我的建議是,從您的組件元數據中刪除moduleId: module.id並再試一次。當它在那裏時,即使是Plunker也不工作。

UPDATE:

「刪除的moduleId的都不在話下。 」分量的相對路徑「 菜譜刪除(2017年3月13日)」 - https://angular.io/docs/ts/latest/guide/change-log.html

app.ts:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <button (click)="method1()">Invoke Method 1</button> 
    </div> 
    `, 
}) 

export class App implements OnInit{ 
    name:string; 
    constructor() { 
    this.name = `Angular! v${VERSION.full}` 
    } 

    ngOnInit(): void { 
    this.method1(); 
    }; 

    method1(): void { 
    this.method2(); 
    }; 

    method2(): void { 
    alert("hi"); 
    } 

} 
相關問題