简体   繁体   中英

How to call one method from another method in same Angular (Typescript) Component Class?

I am seeing a strange error where I try to call a method from another method and both method are in the same Angular 2 TypeScript component.

See in the below code that when ngOnInit() is invoked, it kicks off method1. method1 tries to invoke this.method2() . This is where the issue lies. The error that appears is the following: Error: Cannot read property 'method2' of undefined

Why is the this object undefined? How can I get around this so that I can call methods belonging to a class from other methods in the same class as I would, say in a language like 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");
  }
}

I copied your exact code in this Plunker (but removed the unusual ']' from method2's argument) and it's working fine. I have added a button as well, to invoke Method1() as many times you want.

My suggestion is, remove moduleId: module.id from your component metadata and try again. Even the Plunker doesn't work when its in there.

UPDATE:

"All mention of moduleId removed. "Component relative paths" cookbook deleted (2017-03-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");
  }

}

这是不可运行的,因此我无法自己测试此解决方案,而是尝试将函数重命名为“ this.method2”,而不仅仅是“ method2”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM