JoHksi JoHksi - 5 months ago 34
AngularJS Question

Method chaining in Javascript in Angular app

in my Angular web app, I have a module called

ApplicationModule
.
ApplicationModule
has
get
and
set
functions.

In one of my controllers, I call function like below:

ApplicationModule.get().then(function (response) {
//do something with response
});


GET()
function returns an object called
application
. With the returned object, I would like to do something with it. so I use
then
to chain the method but I get an error saying
angular.js:13424 TypeError: Cannot read property 'then' of undefined
.

Updated what get() is.

ApplicationModule.get = function () {
if (!localStorage.application) {
Restangular.all('session').one('user').get().then(function (response) {
application = {
"id": response.current_application_id,
"user_id": response.id,
"visa_type": response.current_type
}
localStorage.setItem("application", JSON.stringify(application));
return application
});
} else {
return JSON.parse(localStorage.application)
}
}


What am I doing wrong here?

Answer

Your method does neither return the application nor does it return an object at all if localStorage.application is falsy.

You are doing something asynchronous in your function, so you need to always return a promise:

ApplicationModule.get = function () {
    if (!localStorage.application) {
        return Rectangular.all('session').one('user').get().then(function (response) {
//      ^^^^^^ returning the promise
            var application = {
                "id": response.current_application_id,
                "user_id": response.id,
                "visa_type": response.current_type
            };
            localStorage.setItem("application", JSON.stringify(application));
            return application;
//          ^^^^^^ returning the value that the promise will resolve with
        });
    } else {
        return $q.resolve(JSON.parse(localStorage.application));
//             ^^^^^^^^^^ creating a promise here as well for consistent interface
    }
}
Comments