Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a resolved promise from an AngularJS Service using $q?

My service is:

myApp.service('userService', [   '$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {     var deferred;     deferred = $q.defer();     this.initialized = deferred.promise;     this.user = {       access: false     };     this.isAuthenticated = function() {       this.user = {         first_name: 'First',         last_name: 'Last',         email: '[email protected]',         access: 'institution'       };       return deferred.resolve();     };   } ]); 

I'm calling this in my config file via:

myApp.run([   '$rootScope', 'userService', function($rootScope, userService) {     return userService.isAuthenticated().then(function(response) {       if (response.data.user) {         return $rootScope.$broadcast('login', response.data);       } else {         return userService.logout();       }     });   } ]); 

However, it complains that then is not a function. Aren't I returning the resolved promise?

like image 928
user3620820 Avatar asked May 09 '14 14:05

user3620820


People also ask

How do I return a promise in AngularJS?

data) every time to solve promises, instead, you can simply return response. data in then() 's callback. The then() function returns a new promise, so isn't need to use $q to create a deferred object and return a promise. Just return the promise created by then() .

What is Q defer () in AngularJS?

Simply put you can use $q. defer() to create a Promise. A Promise is a function that returns a single value or error in the future. So whenever you have some asynchronous process that should return a value or an error, you can use $q. defer() to create a new Promise.

What is Q in Angular?

$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI. Q has many more features than $q, but that comes at a cost of bytes.

What is resolve in promise Angular?

race() : It waits until any of the promises is resolved or rejected. Promise. reject() : It returns a new Promise object that is rejected with the given reason. Promise. resolve() : It returns a new Promise object that is resolved with the given value.


1 Answers

How to simply return a pre-resolved promise in AngularJS

Resolved promise:

return $q.when( someValue );    // angularjs 1.2+ return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6 

Rejected promise:

return $q.reject( someValue ); 
like image 114
Andrey Mikhaylov - lolmaus Avatar answered Sep 19 '22 13:09

Andrey Mikhaylov - lolmaus