Waiting for a promise to resolve before loading a resource

One of my AngularJS controllers contains this line:

api.tickets.query() 

The api module contains the following:

 angular.module('myapp.api', [ 'ngResource' ]) .factory('api', function($resource, applicationsService) { function fetchAppId() { return applicationsService.getCurrentApp(); } return { tickets: $resource('tickets', { applicationId: fetchAppId }), ... } 

applicationsService.getCurrentApp () makes the $ http call itself. Thus, you can see the problem - this call may not be resolved by the time fetchAppId () returns.

How can I get around this?

+6
source share
3 answers

Suppose the data returned from applicationsService using the async method:

  var data = [ { "PreAlertInventory": "5.000000", "SharesInInventory": "3.000000", "TotalSharesSold": "2.000000" } 

and applicationsService factory returns a promise:

 .factory('applicationsService', ['$resource','$q', function($resource, $q) { var data = [ { "PreAlertInventory": "5.000000", "SharesInInventory": "3.000000", "TotalSharesSold": "2.000000" } ]; var factory = { getCurrentApp: function () { var deferred = $q.defer(); deferred.resolve(data); return deferred.promise; } } return factory; }]); 

I would just call api.tickets()

 $scope.data = api.tickets(); 

but our api service will look like this:

 .factory('api', function($resource, applicationsService,$q, $timeout) { function fetchAppId() { return applicationsService.getCurrentApp(); } return { tickets: function() { var deferred=$q.defer(); fetchAppId().then(function(data) { // promise callback $timeout(function(){ // added dummy timeout to simulate delay deferred.resolve(data); }, 3000); }); return deferred.promise; } } }); 

Fiddle Demo

+6
source

You need to do to create your promise.

 .factory('api', function($resource, applicationsService,$q) { function fetchAppId() { return applicationsService.getCurrentApp(); } return { tickets: function() { var defer=$q.defer(); fetchAppId().then(function(data) { var appId=data; $resource('tickets', {applicationId: appId}) .then(function(data) { defer.resolve(data); }) } return defer.promise; } } 
+4
source

If you want to wait until the angular ( $resource ) $resource is resolved before changing the route, you need to return $promise .

 $routeProvider.when('/tickets', { resolve: { 'tickets': function ('Ticket') { // do this to resolve the async call prior to controller load return Ticket.query().$promise; // this will resolve 'tickets' during/after controller load return Ticket.query(); } }, controller: ... }); 
+1
source

Source: https://habr.com/ru/post/956700/


All Articles