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?
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() .
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.
$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.
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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With