'Emberjs Model from route returning undefined in controller

I have a strange behavior with my Ember app. I can't make any sense out of it. Basically I'm using Ember octane and I wanted to access my model from my route to my controller .

This is my route

import Route from '@ember/routing/route';

export default class ChatIndexRoute extends Route {
  model() {
    return {
      chatMessages: [
        {
          username: '1',
          message: 'Hi',
          read: true,
        },
        {
          username: '1',
          message: 'how are you?',
          read: false,
        },
        {
          username: '1',
          message: 'its been a long time :)',
          read: false,
        },
      ],
    };
  }

  setupController(controller, model) {
    controller.set('model', model.chatMessages);
  }
}

and this is my controller

import Controller from '@ember/controller';


export default class ChatIndexController extends Controller {
  init() {
    super.init(...arguments);
    console.log('test', this.model);
  }
}

When I console.log(this.model) I got undefined.

But when I simply do a console.log(this) I got a whole object with a model property filled with chatmessages

See this image

This is crazy



Solution 1:[1]

This is just a little timing confusion. init() on the controller is executed before setupController on the route. so this.model is undefined.

But when you do console.log(this) you get the complete controller logged. And the magic of the console is that it is live. So when this object later (not much later, just a tiny little bit) will be updated, you will see it in the console. And so you can inspect the model property on the controller in the console, even if it wasnt there when you logged the controller.

Solution 2:[2]

One workaround for this would be using the model directly in template, and another work around is using computed properties.

export default class ChatIndexController extends Controller {
  init() {
    super.init(...arguments);
    console.log('test', this.model);
  }
  chatMessages: computed(function(){
     console.log(this.model); //will print the model
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lux
Solution 2 Arafath Baig