1

Right now, I want to be able to set some data for a service, and to be able to get the data on a second controller. I saw on my debugger, that the code isn't working correctly because my logic isn't asynchronous.

myApp.factory('Data', function($http) {

var storage;

this.callMe = function() {
    return $http.get("https://api.github.com");
};

this.getStorage = function() {
    return storage;
};

this.setStorage = function(v) {
    storage = v;  
};

return this;

});

function FirstCtrl($scope, Data, $q) {
Data.callMe().then(function(response) {
    $scope.data = response.data;
});
Data.setStorage($scope.data);
}

function SecondCtrl($scope, Data) {

var data = Data.getStorage();

}

I have a plnkr: http://plnkr.co/edit/0FicRx9FVJfeWFZhO4Ya?p=streamer

I tried using $q.defer, but I wasn't able to get the effect I wanted.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
user1413969
  • 1,261
  • 2
  • 13
  • 25
  • This is the exact same issue - only in Angular - you definitely _should_ read the linked question. It will hopefully clarify a lot of things. – Benjamin Gruenbaum Oct 06 '14 at 14:26
  • 1
    @BenjaminGruenbaum: I thought we'd rather close it as a dupe of one of these promise caching questions, I only couldn't find the right one – Bergi Oct 06 '14 at 14:28
  • @Bergi yeah that is probably the right duplicate... Current marked duplicate is not really the one in the context of the question. – PSL Oct 06 '14 at 14:28
  • @Bergi his problem is not with caching a promise though - it's with understanding how asynchronous execution and concurrency works in browser JavaScript. He is having the same problem as in "How to return the response from an AJAX call" and the solution is the same. Although if either of you can find a better dupe be my guest - you both have hammers :) – Benjamin Gruenbaum Oct 06 '14 at 14:30
  • 1
    Here is a demo how you can cache promise result: http://plnkr.co/edit/PjDChrmDUkLtHZUO46IT?p=preview – dfsq Oct 06 '14 at 14:31
  • @BenjaminGruenbaum I am sure you yourself will have best of promise related answers which covers both the scenarios :) Haven't seen better ones from anybody else yet.. :D – PSL Oct 06 '14 at 14:32
  • 1
    @PSL I appreciate the positive feedback and I do put a lot of effort. I'm just still not convinced any of my answers are better at explaining the underlying issue. I've considered adding a second answer to "How to return the response from an AJAX call" using promises or asking a similar but promise based question about JS concurrency but I was never satisfied with the results and I really like Felix's answer on that question. I'm all up for suggestions though. – Benjamin Gruenbaum Oct 06 '14 at 14:34

0 Answers0