2017-04-23 35 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'周围值的箭头函数。或者用'const self = this;'在'authenticate'方法的顶部捕获'this'的这个值,然后使用'self.set'。 – 2017-04-23 04:47:48

+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); 
     }); 
    }); 
    }); 
}, 
相关问题