2017-04-23 9 views
0

userSessionStorageに値を設定しようとしていますが、authenticate()関数からアクセスしているときに正しく動作しているようです。ember:TypeError:未定義のプロパティ 'set'を読み取ることができません

ただし、.then()約束では機能しません。

アプリ/コントローラ/ show.js

import Ember from 'ember'; 
import { storageFor } from 'ember-local-storage'; 

export default Ember.Controller.extend({ 
    session: Ember.inject.service('session'), 

    userSessionStorage: storageFor('user'), 

    authenticator: 'authenticator:custom', 

    actions: { 
    authenticate: function() { 
     var credentials = this.getProperties('identification', 'password'); 
     // ok 
     this.set('userSessionStorage.username', credentials.identification); 

     this.get('session').authenticate('authenticator:custom', credentials) 
     .then(function(){ 

      // error: TypeError: Cannot read property 'set' of undefined 
      this.set('userSessionStorage.username', credentials.identification); 

     }) 
     .catch((message) => { 
      console.log("message: " + message); 

      this.controller.set('loginFailed', true); 
     }); 
    } 
    } 
}); 
+2

'then'に渡す関数を、' this'の周囲の値を保持する矢印関数として書き換えます。あるいは 'this self'のこの値を' authent self = this; 'で' authenticate'メソッドの先頭に取り込み、 'self.set'を使います。 –

+0

@torazaburoあなたは良いです:)私は正しい答えとしてそれを置くことができるようにあなたは答えとしてこれを置くことができますか? –

+0

オーセンティケータに 'userSessionStorage.username'を設定してみませんか? –

答えて

1

あなたがする必要があるすべては次の行を変更している次のように脂肪の矢印表記を使用する

this.get('session').authenticate('authenticator:custom', credentials) 
     .then(function(){....} 

を:

this.get('session').authenticate('authenticator:custom', credentials) 
     .then(()=>{....} 

したがって、約束コンテキスト内のthisコンテキストがコントローラになります。 ES6矢印機能の詳細については、followingを参照してください。

1

それは、私自身のコードに基づいているので、あなたはそれを適応させる必要がある場合があります。しかし、あなたのオーセンティケータに、あなたのauthenticate機能は次のようになります。

# authenticator 

authenticate(credentials) { 
    const { identification, password } = credentials; 
    const data = JSON.stringify({ 
    auth: { 
     email: identification, 
     password 
    } 
    }); 

    const requestOptions = { 
    url: this.tokenEndpoint, 
    type: 'POST', 
    data, 
    contentType: 'application/json', 
    dataType: 'json' 
    }; 

    return new Promise((resolve, reject) => { 
    ajax(requestOptions).then((response) => { 
     // Set your session here 
    }, (error) => { 
     run(() => { 
     reject(error); 
     }); 
    }); 
    }); 
}, 
関連する問題