3gwebtrain
3gwebtrain

Reputation: 15303

EmberJS - Not able to get property from "service' from Component

In my ember application, I am trying to retrieve the data from service to component, but I am getting an error as :

TypeError: this.start.toggleProperty is not a function - But i have a property there is service.

Here is my component js :

import Ember from 'ember';

export default Ember.Component.extend({
    start: Ember.inject.service( ),
    message: null,
    actions: {
        pressMe() {
            this.start.toggleProperty('isOn'); //throws error
            // this.set('message',this.start.importantInfo( ));
            // Ember.log(this.start.isOn);
            console.log( "start is", this.start.isOn ); //undefined!?
        }
    }
});

Here is my service js :

import Ember from 'ember';

export default Ember.Service.extend({
    isOn: false,
    importantInfo( ){
        return "Important Info is " + this.get('isOn');
    }
});

Do I missed something? any one suggest me the correct way please? Thanks in advance.

Upvotes: 0

Views: 270

Answers (1)

Ember Freak
Ember Freak

Reputation: 12872

Answer is,

this.get('start').toggleProperty('isOn')

Reason is,

Injected properties are lazy loaded; meaning the service will not be instantiated until the property is explicitly called. Therefore you need to access services in your component using the get function otherwise you might get an undefined.

Reference:
https://guides.emberjs.com/v2.14.0/applications/services/#toc_accessing-services

Upvotes: 1

Related Questions