0

I have the following JavaScript code in my service layer. When this code executes, I get an error saying - Cannot read property 'then' of undefined. I looked at some other similar posts on stackoverflow but still couldn't resolve this issue.

Question: What code changes will correct the above error? May be I am calling something in AngularJS the wrong way but not sure.

      function getPreferenceSet(type) {
        var t = angular.isString(type) ? type : '';
        logger.info('getPreferenceSet: fetching; type: ' + t);

        var route = userPreferenceConstants.endPoints.PREFERENCE + '?type=' + t;

        var allDashboardsDeferred = false;
        if (!allDashboardsDeferred) {
            allDashboardsDeferred = $http.get(route)
                .then(getPreferenceSetComplete)
                .catch(function (message) {
                    exception.catcher('XHR failed for getPreferenceSet')(message);
                });
        }
        return allDashboardsDeferred.promise;

        function getPreferenceSetComplete(response) {
            logger.info('getPreferenceSet: complete');
            return response.data;
        }
    }
5
  • 1
    When you set allDashboardsDeferred it's already set to a promise so I'd guess allDashboardsDeferred.promise is not defined and something above is calling .then on the result. Try updating to return allDashboardsDeferred; Commented May 15, 2015 at 16:32
  • Also the then can take a 2nd function for errors .then(getCompleteFn,getErrorFn) and you can log out if you are getting an error. Commented May 15, 2015 at 16:42
  • @trevor, Yes, all dependencies are injected. Commented May 15, 2015 at 16:46
  • Do I need to call resolve method somewhere for the promise? Commented May 15, 2015 at 16:47
  • No, you don't need to call resolve. You're just returning (and chaining) the promise returned from $http.get and that function resolves the promise when the call completes. Commented May 15, 2015 at 16:49

1 Answer 1

1

The call to $http.get(route).then(...).catch(...) is returning an HttpPromise that resolves when the call completes. The allDashboardsDeferred variable is a promise already and not a deferred so you can return it directly:

return allDashboardsDeferred; 
Sign up to request clarification or add additional context in comments.

1 Comment

I will try this out and let you know. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.