How to define a function in Ionic 2

2019-09-22 08:29发布

问题:

I cannot define a simple function in Ionic 2. This is my code:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';  

@Component({
    selector: 'page-account',
    templateUrl: 'account.html'
})
export class AccountPage {

    function show() //←THIS FUNCTION
    {
        alert("show");
    }

    constructor(public navCtrl: NavController, public navParams: NavParams) {}

}

then this is the error in the web browser:

I'm using ionic 2.2.0.

Thanks for your help.

回答1:

Remove the function

Just make your code:

show() //Return type would be `show(): string` f.e.
{
    alert("show");
}


回答2:

Remove function from function show()

export class AccountPage {

    constructor(public navCtrl: NavController, public navParams: NavParams) {
    }


    show() //←THIS FUNCTION
    {
        alert("show");
    }
}


回答3:

In ionic 2. You can directly start your the function from it's name itself without needing to declare "function" as prefix.

Similarly with ionic life cycle functions. You can see more on this function's declaration syntax in this link: http://www.ionichelper.com/2016/10/11/ionic-2-components-quick-guide-series-app/