简体   繁体   中英

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. 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:

Uncaught TypeError: undefined is not a function

Here's the initializer for the Ember app:

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):

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):

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!

you probably wanted to write:

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

Does this help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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