2017-11-14 6 views
0

Ionic FrameworkでPOCをいくつか実行していて、ActionSheetとActionSheetControllerを使用する必要がありました。すべてがうまくいくようですが、クラスで定義した関数をハンドラに割り当てると、奇妙なエラーが発生しました。奇妙なのは、コンソールログを置いたときに関数を呼び出すことができるということですが、私が注入したクラス変数やサービスがその関数で使用または参照されている場合はエラーとなります。私のサービスやクラス変数は未定義です。以下のコードを参照してください:ActionSheetハンドラーがクラス変数にアクセスできない

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を呼び出すとき、それは完璧に動作することが見つかりました:1つの作品やその他がなかった理由を

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(); 
} 

することは、誰かが私に説明できますか?違いは何ですか?

ありがとうございました。

EDIT:これは私は、構文@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'. 
+0

私の答えが役に立ったら、それを正しく、ありがとうとマークしてください。 – ewizard

+0

あなたが同じシステムに戻ってきたときに私に知らせて、エラーを読むことができます。 – ewizard

答えて

0

あなたの最初の例では、handler: this.addToFavorites()が欠落しています。それは:

this.addToFavorites()である必要があります。

+0

私はしようとしたが、構文について不平を言う。今私は、私が現在取り組んでいるシステムにアクセスできないので、どのようなエラーが表示されたのか覚えていません。私はそれにアクセスするとエラーを確認します。そして、関数を呼び出すことができたので、構文や欠落()は問題ではないと思います。クラス変数にアクセスできませんでした。 – zhaider

+0

提案した構文を使用したときにVSコードがスローするエラーを反映するように元の投稿を更新しました。 – zhaider

+0

このエラーは、このようにすることができないと思います。ハンドラの後に '()=> {function()}'を使う必要があります。 – ewizard

関連する問題