0

i want to share data that i get from the lastFM API between two controllers.

I've been trying with the factory but I don't get a grip on it...

angular.module('myApp')
  .factory('getData', function($http, $scope, $routeParams) {
    $http.get(lastfm + "&method=artist.getInfo&mbid=" + $routeParams.mbid).success(function(data) {
      console.log(data)
    });
  })
  .controller('artistCtrl', function ($scope, $routeParams, $http, getData) {
    console.log(getData.data);
  })
  .controller('artistInfoCtrl', function ($scope, $routeParams, $http, getData) {
    console.log(getData.data);
  })

So how do i manage to pull this off?

2 Answers2

1

There are a couple of things:

1) know that you're dealing with asynchronous data, so do not expect to be able to read the data in the controllers immediately.

2) have your factory return a function that the controllers can call. This function should return a promise that will eventually (if all goes well) be resolved with the data;

3) the controllers can call this function that is returned by the factory and in the .then() of the promise that is returned, you can actually work with the data.

My advice is to do a little research on the terms I described above, if they are not yet familiar to you. Understanding them will enable you to achieve a lot more with angular.

Walter Brand
  • 679
  • 3
  • 9
0

Your factory has no property data, you probably need to call your factory by saying

var something = getData();

and make the success handler of the $http call return that data

$http.get(lastfm + "&method=artist.getInfo&mbid=" + $routeParams.mbid).success(function(data) {
      return data;
    });
ruedamanuel
  • 1,930
  • 1
  • 22
  • 23