ember:TypeError:无法读取未定义的属性'set'

时间:2017-04-23 04:23:36

标签: javascript ember.js

我正在尝试将值设置为userSessionStorage,当我从authenticate()函数访问它时,它似乎正常工作。

但是,它不适用于.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 个答案:

答案 0 :(得分:2)

您需要做的就是更改以下行:

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

使用胖箭头表示法如下:

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

以便promise上下文中的this上下文将成为您的控制器。有关ES6箭头功能的更多信息,请参阅following

答案 1 :(得分: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);
      });
    });
  });
},