Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ember.js 如何设置应用程序范围的变量?(在应用程序控制器上?)_Ember.js - Fatal编程技术网

Ember.js 如何设置应用程序范围的变量?(在应用程序控制器上?)

Ember.js 如何设置应用程序范围的变量?(在应用程序控制器上?),ember.js,Ember.js,我正在使用最新的Ember 2.1,我想知道如何在应用程序控制器上设置一些应用程序范围的变量,例如用户id、用户名、电子邮件等 虽然ember应用程序有很多文件,但我还没有做很多工作,我有点自信我正在共享正确的代码。我没有登录路径文件。我已经安装了ember simple auth插件,但实际上我并没有以任何特殊方式使用/调用它,只是将其混合到我的应用程序路径中: import ApplicationRouteMixin from 'simple-auth/mixins/application-

我正在使用最新的Ember 2.1,我想知道如何在应用程序控制器上设置一些应用程序范围的变量,例如用户id、用户名、电子邮件等

虽然ember应用程序有很多文件,但我还没有做很多工作,我有点自信我正在共享正确的代码。我没有登录路径文件。我已经安装了ember simple auth插件,但实际上我并没有以任何特殊方式使用/调用它,只是将其混合到我的应用程序路径中:

import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin)
我的路由器:

this.route('login')
我的登录模板:

<button {{action 'forceLogin'}}>Force login of devinrhode2@gmail.com by clicking this action button</button>
<p>Your account id is: {{account_id}}</p>
我调用了
forceLogin
控制器操作,但是
{{{account\u id}}
没有填充到模板中。如何将要渲染的帐户id恢复到模板中?我如何通过调用this.get('account\u id')使我的余烬应用程序可以全局访问account\u id,无论我在哪里需要它

目前我得到了一个错误:

 Cannot read property 'setProperties' of undefined

由于定义
forceLogin
的方式,会出现错误。箭头函数绑定到定义它们的上下文。以下是您的代码编译的目的:

var _this = this; // we capture `this` from out here!
export default Ember.Controller.extend({
  actions: {
    forceLogin() {
      ...
      _this.setProperties(data) // `_this` is the window!
    }
  }
});
这是不好的,因为
这个
应该是控制器的实例,而是
窗口

相反,您应该这样定义
forceLogin

export default Ember.Controller.extend({
  actions: {
    forceLogin() {
      ...
      this.setProperties(data) // `this` is our controller instance
    }
  }
});

要从其他地方获取
帐户\u id
,可以插入登录控制器:

export default Ember.Controller.extend({
  actions: {
    forceLogin: () => {
      var data = {
        "account_id": 123,
        "email":"devinrhode2@gmail.com",
        "name":"Devin Rhode"
      }
      this.setProperties(data)
    }
  }
});
// in some other controller
export default Ember.Controller.extend({
  login: Ember.inject.controller(),

  actions: {
    doSomethingWithTheAccountId() {
      var accountId = this.get('login.account_id');
      ...
    }
  }
});

将这些属性移动到服务中会更干净,您可以使用
Ember.inject.service()

在任何地方注入服务,非常感谢@dwickern。我一直认为箭头函数只是语法上的糖,所以我会在这上面停留很长一段时间,寻找所有错误的地方。顺便说一句。。实际上,我应该做的是在ember simple auth的会话对象(可能是服务..idk)上设置这些变量