2

I am trying to read data from json and wait until data will be fetched into $scope.urls.content. So I write code:

$scope.urls = { content:null};
$http.get('mock/plane_urls.json').success(function(thisData) {
    $scope.urls.content = thisData;    
});

And now I am trying to write something like callback but that doesn't work. How can i do that? Or is there any function for this? I am running out of ideas ;/

3
  • 1
    What you wrote already contains a callback. Explain what you're trying to achieve please. Commented Jul 19, 2013 at 13:38
  • 1
    What you see in networking tab of dev tools, do you ever have response from server ? is it with code 20x ? You are only defining success call back, which means it won't be fired in case of failure. Commented Jul 19, 2013 at 13:39
  • I am trying to use data what was fetched into $scope.urls.content but every time when i try use it immediately they have null. Commented Jul 19, 2013 at 13:51

2 Answers 2

2

Do you mean that ?

$http.get('mock/plane_urls.json').success(function(thisData) {
    $scope.urls.content = thisData;
    $scope.yourCallback();
});
$scope.yourCallback = function() {
   // your code
};
Sign up to request clarification or add additional context in comments.

2 Comments

I'm sure that yourCallBack would take a parameter of the returned data :).
I believe it should be better to use promise API instead of calling a callback directly. It was designed for these needing..
1

You want to work with promises and $resource.

As $http itself returns a promise, all you got to do is to chain to its return. Simple as that:

var promise = $http.get('mock/plane_urls.json').then(function(thisData) {
  $scope.urls.content = thisData;
  return 'something';
});

// somewhere else in the code
promise.then(function(data) {
  // receives the data returned from the http handler
  console.log(data === "something");
});

I made a pretty simple fiddle here.

But if you need to constantly call this info, you should expose it through a service, so anyone can grab its result and process it. i.e.:

service('dataService', function($http) {
  var requestPromise = $http.get('mock/plane_urls.json').then(function(d) {
    return d.data;
  });

  this.getPlanesURL = function() {
    return requestPromise;
  };
});

// and anywhere in code where you need this info
dataService.getPlanesURL().then(function(planes) {
  // do somehting with planes URL
  $scope.urls.content = planes;
});

Just an important note. This service I mocked will cache and always return the same data. If what you need is to call this JSON many times, then you should go with $resource.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.