Using ngDreamFactory module: Getting error “TypeError: Cannot read property 'login' of undefined”

Thats true, i’ll pass this along to those who got that blog and sample together.

Hi Christian, Your thread seems to have been hijacked. I wanted to reach out to answer your question. Your getting an undefined error because your calling login when the controller loads. Angular-Dreamfactory builds dynamically when it is injected into the controller and needs time to create the api. That being the case you would need to wrap the login call in function and call it when you want to log a user in. See my example below:

$scope.login = function() {
   DreamFactory.api.user.login($scope.creds,
        function (data) {
            console.info('Login success');
            $scope.getApartments();
        },
        function (error) {
            console.info('Login failed')
        }
    );
}

You can also call DreamFactory.isReady() which will return a boolean to test by. Here is an example of that using an Angular promise:

if (DreamFactory.isReady()) {
    // make api call
    DreamFactory.api.db.getResources().then(
        function(result){ // handle result},
        function(reject){ // handle reject}
    );
}

If you did want to use the api to fire a function when the controller loads you have to listen for the ‘api:ready’ event. See example below:

.controller('SomeCtrl', ['$scope', function ($scope) {
    
    $scope.$on('api:ready', function(event) {

        DreamFactory.api.db.getResources().then(
            function(result){ //handle result},
            function(reject){// handle reject)
        )
    }
}]);

Now when angular-dreamfactory loads the controller will fire the function. These patterns will help you avoid the ‘undefined’ error that is caused by the live sdk not being available on route/controller load.

1 Like

@einarbmag

The ‘undefined’ error is caused by trying to invoke a method from angular-dreamfactory before it has completely loaded. Because it is built dynamically whenever it is injected it’s functions can’t be assigned directly to a variable. Please take a look at my answer for Christian about how to avoid the ‘undefined’ error when using angular-dreamfactory. I will look into the trivia app as to why it is not working as expected.

Hi michaelmandato,

I am using the ‘api-ready’ method to fire a function when controller is load. The issue I am facing is the data does not loads on the first attempt. Only when I refresh the page the service is fired and data is loaded. Any idea why this is happening?

Hi @jayp, referring to this post, we have had success using something like

$scope.$on('api:ready', function (e) {
   // Code goes here
});