0

我正在尝试在商店内存储一些登录后的数据。下面是我的 torii 适配器的代码

import Ember from 'ember';
import {createToken} from 'myapp/utils/app-utils';

export default Ember.Object.extend({
  store: Ember.inject.service(),

  open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then(function(data){
      let user = data.user[0];
      this.set('storage.token',token); //this is undefined
      return {
        user: user
      };
    });
  }

});

我得到的错误是“TypeError:无法读取未定义的属性'set'”。我也在注入商店服务。你能告诉我这里到底出了什么问题吗?

4

2 回答 2

0

this未在您当前的上下文中定义。将其分配给另一个变量。

  open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    let that = this;
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then(function(data){
      let user = data.user[0];
      that.set('storage.token',token); //this is undefined
      return {
        user: user
      };
    });
  }

要进一步了解并查看不同的选项(例如胖箭头绑定方法),请查看此问题

于 2017-02-26T17:59:58.810 回答
0

另一种方法是使用 ES6 箭头函数,这样就不需要分配this其他变量。

 open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    let that = this;
    return new Ember.RSVP.Promise((resolve, reject) => {
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then((data) => {
      let user = data.user[0];
      that.set('storage.token',token);
      return {
        user: user
      };
    });
  }

Ember-cli 将帮助您将 ES6 转换为 ES5,使其与大多数浏览器兼容。

于 2017-02-26T23:40:12.023 回答