1

alert-service.ts

 public Alert = {
        prompt: () => {
          return new Promise((resolve, reject) => {
            let prompt = this.alertCtrl.create({
              title: 'Enter username',
              inputs: [
                {
                  name: 'username',
                  placeholder: 'Username'
                },
              ],
              buttons: [
                {
                  text: 'Cancel',
                  handler: data => {
                    reject(false);
                  }
                },
                {
                  text: 'Save',
                  handler: data => {
                    console.log(data);
                    resolve(data);
                  }
                }
              ]
            });
            prompt.present();
          });
        }
      }

request-service.ts

function () {
    this.prompt.Alert.prompt().then((res) => {
           this.user.username = res;
           alert(this.user.username);
    }, err => {
          this.alertService.Alert.alert('user_cancelled', 'Error');
    }); 
}

This runs in the browser when I use IONIC Serve, but it's not working on a device. I'm getting Can not read property 'prompt' of undefined

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Don't use `function () {` in your `request-service.ts` It should br either arrow function or method – yurzui Dec 14 '17 at 09:58

1 Answers1

0

When you type that

function () {
    this.prompt.Alert.prompt().then((res) => {
          this.user.username = res;
          alert(this.user.username);
    }, err => {
          this.alertService.Alert.alert('user_cancelled', 'Error');
    }); 
}

You don't use the Typescript fat arrow function. If you don't want to use fat arrows, you have to use Javascript closures to get the right context for the this keyword.

Right now, the this keyword is referencing your function, not your object.

EDIT Example for closures :

In a typescript class :

x = 'Hey baby';
let fatArrowFunction= () => console.log(this.x); // "Hey baby"
that = this;
let usualFunction = function() {
  let x = 'Hey sweetheart';
  console.log(x); // "Hey sweethearth"
  console.log(this.x); // "Hey sweethearth"
  console.log(that.x); // "Hey baby"
}