jazzblue jazzblue - 9 months ago 38
AngularJS Question

Switching AngularJS views while waiting for promise

I have the following code (see below) where MyCtrl1 is a controller of a view that the app is routed to depending on URL. The controller calls a function in a models service which returns a promise from an http request. The model is supposed to log something in another service responseService, based on response and return promise to controller. If the http response takes a while I need the user to be able to switch views through the URL and still having the model working on request until it is done. here are my questions:

If the user switches view in the middle of the http request:


  1. the MyCtrl1 is gone, i.e. the next time user switches back to
    the MyCtrl1 view it would not remember the call and the
    promise would not be returned to it, correct?

  2. Is the model service still be working on http request and update
    responseService when response is received?

  3. If the latter is "no", the how can I make it work? I need the user
    to be able to switch views while the http is working.



Thanks!

myctrl1.controller.js:

angular.module('myApp')
.controller('MyCtrl1', ['$scope', 'myModels', function ($scope, myModels) {

myModels.listMyData().then(
function(response) {
...
},
function(response) {
...
}
);
}]);


myModels.models.js:

angular.module('myApp')
.service('myModels', ['$http', '$q', 'responseService', function($http, $q, responseService) {

this.listMyData = function() {

var promise;
...

$http.get('http://xxx.xxx.xxx').then(
function(response) {
// register something in responseService
// assign promise
},
function(response) {
// register something in responseService
// assign promise
}
);

return promise;
}

}]);

Answer

You can say that objects/functions in javascript are deleted only if they are not referenced. When you call:

$http.post(...).then(callback)

callback function is now referenced. So it wont be deleted and it will execute disregarding if user switches view. Answering your questions: 1. Yes 2. Yes