Thomas Cauquil
Thomas Cauquil

Reputation: 11

Ionic import module

I have a problem with ionic, angular, typescript, i get lost a little ...

I would like to call an external function to my file but I get the error: "Uncaught (in promise): TypeError: undefined is not an object (evaluating 'this.alertCtrl.create') popup"

Here is my main file:

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

import { params } from '../../modules/params';

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

  params = new params();

  constructor(public navCtrl: NavController) {
    this.params.popup("Hello", "test");
  }

}

As well as the page containing the function:

import { AlertController } from 'ionic-angular';

export class params {
    public alertCtrl: AlertController;
    constructor(){

    }

    popup(title, text){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: text,
            buttons: ['OK']
        });
        alert.present();
    }
}

Where would I be wrong? Thank you very much for your help.

Upvotes: 0

Views: 304

Answers (2)

Petrus Cyrino
Petrus Cyrino

Reputation: 204

my friend.

You'll first need to add the @Injectable() decorator in the class that contains the function you want to use. For example:

import { Injectable } from '@angular/core';
import { AlertController } from 'ionic-angular';

@Injectable()
export class params {

    constructor(public alertCtrl: AlertController){

    }

popup(title, text){
    let alert = this.alertCtrl.create({
        title: title,
        subTitle: text,
        buttons: ['OK']
    });
    alert.present();
}
}

Then you'll just need to inject the variable in your constructor to call it in your page like this:

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

import { params } from '../../modules/params';

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

  constructor(public navCtrl: NavController, public params: params) {
    this.params.popup("Hello", "test");
  }

}

Hope I could help you! =)

Upvotes: 0

Andrew Lively
Andrew Lively

Reputation: 2153

For the injection to work properly you must pass it as a constructor param:

import { AlertController } from 'ionic-angular';

export class params {
    constructor(public alertCtrl: AlertController) {

    }

    popup(title, text){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: text,
            buttons: ['OK']
        });
        alert.present();
    }
}

What you had before was the declaration of a public property called alertCtrl of type AlertController, but it was never being initialized, so that's why you got the undefined error.

Upvotes: 1

Related Questions