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

时间:2022-03-02 21:05:57

I have an initializer for my Ember application and I've registered/injected a currentUser object into all of my controllers and routes. The initializer seems to be working, because I was able to access the currentUser in my Application Route. However, when I tried to access the currentUser object in an ObjectController, I get the following error:

我有一个初始化器用于我的Ember应用程序,我已经注册/注入了一个currentUser对象到我的所有控制器和路由中。初始化程序似乎正在工作,因为我能够访问应用程序路由中的currentUser。但是,当我尝试访问ObjectController中的currentUser对象时,我收到以下错误:

Uncaught TypeError: undefined is not a function

未捕获的TypeError:undefined不是函数

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(这是正常的 - 我能够在我的Handlebar模板中访问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? Or is there something wrong with my initializer setup?

我到底错在了什么?这是一个引用的问题吗?或者我的初始化程序设置有问题吗?

Thanks in advance!

提前致谢!

1 个解决方案

#1


1  

you probably wanted to write:

你可能想写:

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

Does this help?

这有帮助吗?

#1


1  

you probably wanted to write:

你可能想写:

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

Does this help?

这有帮助吗?

相关文章