ActionSheet处理程序无法访问类变量

时间:2017-11-14 15:27:18

标签: angular ionic-framework callback handler

我在Ionic Framework上做了一些POC,我需要使用ActionSheet和ActionSheetController。一切似乎都有效,但是当我为一个处理程序分配一个我在类中定义的函数时,我遇到了一个奇怪的错误。奇怪的是,它可以调用函数,因为我已经放置了控制台日志,但如果函数使用或引用我注入的任何类变量或服务,它会抱怨并抛出错误。它说我的服务或类变量未定义。请参阅以下代码:

addToFavorites() {
console.log('Adding to Favorites', this.game.id);
this.favorite = this.favoriteservice.addFavorite(this.game.id);
this.toastCtrl.create({
  message: this.game.id + ' added as favorite successfully',
  position: 'middle',
  duration: 3000}).present();
}

presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
  title: 'Select Actions',
  buttons: [
    {
      text: 'Add To Favorites',
      handler: this.addToFavorites
    },
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }
  ]
}); 
actionSheet.present();
}

两者都是在页面类中定义的函数,我注入了favoriteService,游戏是类变量。当我调用addToFavorites时,我发现它可以完美地工作:

presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
  title: 'Select Actions',
  buttons: [
    {
      text: 'Add To Favorites',
      handler: () => {
        this.addToFavorites();
      }
    },
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }
  ]
}); 
actionSheet.present();
}

有人可以向我解释为什么一个有效,另一个没有?有什么区别?

感谢。

编辑:这是我使用@ewizard建议语法时出现的错误:

[ts]
Argument of type '{ title: string; buttons: ({ text: string; handler: void; } | { text: string; handler: () => void...' is not assignable to parameter of type 'ActionSheetOptions'.
Types of property 'buttons' are incompatible.
Type '({ text: string; handler: void; } | { text: string; handler: () => void; } | { text: string; role...' is not assignable to type '(string | ActionSheetButton)[]'.
  Type '{ text: string; handler: void; } | { text: string; handler: () => void; } | { text: string; role:...' is not assignable to type 'string | ActionSheetButton'.
    Type '{ text: string; handler: void; }' is not assignable to type 'string | ActionSheetButton'.
      Type '{ text: string; handler: void; }' is not assignable to type 'ActionSheetButton'.
        Types of property 'handler' are incompatible.
          Type 'void' is not assignable to type '() => boolean | void'.

1 个答案:

答案 0 :(得分:0)

在您的第一个示例中,您遗漏了()中的handler: this.addToFavorites。它应该是:

this.addToFavorites()