简体   繁体   中英

How to call get method from a class in Angular 2

I'm using class data model in Angular 2.

In my Home component, I'm receiving data from a server and storing in that classes.

My question is, I have now the get methods created, like:

@Injectable()
export class Menu {
  name: string;
  categories: { [name: string]: Category };

  constructor(data: { name: string }) {
    this.name = data.name;
    this.categories = {};

    Object.keys(data).forEach(name => {
      if (name !== "name") {
        this.categories[name] = new Category(data[name]);
      }
    });
  }

  getName(){
    console.log("Menu name: " + this.name);
  }
}

How can I call this getName method from my Home component?

In my Home component I have:

  getMenus() {
    this.globals.getMenus().subscribe(
      data => {
        this.menus = {};
        Object.keys(data).forEach(name => {
              this.menus[name] = new Menu(data[name]);
        });
        **this.menus.getName();**
        console.log(this.menus);
      },
      err => { console.log(err) }
    );
  }

this.menus.getName() throws me an error, it says: "Property getName() does not exist on type'{[name: string]: Menu;}'"

However, console.log(this.menus) print me all the Menu objects correctly (with field name, and category field (that allows objects of type Category).

在此处输入图片说明

I know probably i'm doing this wrong, but I dont' know any other way to do it.

Any idea?

Thanks.

In your case this.menus is an object, which contains many Menu's . But you call your getName() on that object which contains Menus

You need to call like this.menus.yourName.getName()

You just dol like this

get getName(){

return this.name;

}

your home component:-

import menu component hear

git id let a = Menu.getName;

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