简体   繁体   English

灰烬-无法访问控制器中的注入对象

[英]Ember - Can't access injected object in controller

I have an initializer for my Ember application and I've registered/injected a currentUser object into all of my controllers and routes. 我有一个用于Ember应用程序的初始化程序,并且已将currentUser对象注册/注入到我的所有控制器和路由中。 The initializer seems to be working, because I was able to access the currentUser in my Application Route. 初始化程序似乎正在工作,因为我能够在我的应用程序路由中访问currentUser However, when I tried to access the currentUser object in an ObjectController, I get the following error: 但是,当我尝试在ObjectController中访问currentUser对象时,出现以下错误:

Uncaught TypeError: undefined is not a function

Here's the initializer for the Ember app: 这是Ember应用程序的初始化程序:

Ember.Application.initializer({
  name: 'currentUserLoader',

  initialize: function(container, application) {

    application.deferReadiness();

    Ember.$.ajax('http://localhost:5000', {
      type: 'GET',
      dataType: 'json',
      success: function(data) {
        var user = Ember.Object.create().setProperties(data[0]);

        container.register('user:current', user, {instantiate: false, singleton: true});

        container.injection('route', 'currentUser', 'user:current');
        container.injection('controller', 'currentUser', 'user:current');

        application.advanceReadiness();
      },
      error: function(err) {
        console.log(err);
      }
    });

  }
});

Here's the ApplicationRoute (and this is working correctly - I'm able to access currentUser in my Handlebar templates): 这是ApplicationRoute(并且此方法正常工作-我能够在我的车把模板中访问currentUser ):

App.ApplicationRoute = Ember.Route.extend({
  model: function() {
    return Ember.RSVP.hash({
      currentUser: this.get('currentUser')
    });
  }
});

Here's my ObjectController (and here, it isn't working and throwing an error instead. NOTE: I know this Controller looks pointless right now, but this is more of a proof of concept for the injection, because we can't seem to get the injection working at all): 这是我的ObjectController(在这里,它无法正常工作并引发错误。注:我知道此Controller现在看起来毫无意义,但这更多是注入的概念证明,因为我们似乎无法获得注射工作):

App.ConnectController = Ember.ObjectController.extend({
  currentUser: this.get('currentUser'), // throws an undefined error
});

What exactly am I doing wrong here? 我到底在做什么错? Is it an issue with the reference of this ? 它是与参考的一个问题this Or is there something wrong with my initializer setup? 还是我的初始化程序设置有问题?

Thanks in advance! 提前致谢!

you probably wanted to write: 您可能想写:

App.ConnectController = Ember.ObjectController.extend({
  currentUser: Ember.computed.alias('currentUser')
});

Does this help? 这有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM