0

I am using a factory to make GET requests to social media APIs. This is working fine, and showing the data in the views, however when I inspect in the console it makes the GET request twice, for each individual GET request. This means that at times it displays the data twice in the front end.

Can anyone explain why this is happening? I imagine it may be to do with the way I am implementing the factory.

See code below. If there is anything else that needs to be clarified please let me know. Thanks!

factory

app.factory('socialMedia', ['$http', function($http) {
    return {
      fetchFlickr: function() {
        var self = this;
        return $http.jsonp("https://api.flickr.com/services/feeds/photos_public.gne?tags=sonymusic&tagmode=alll&format=json&jsoncallback=JSON_CALLBACK");
      },

      fetchTwitter: function() {
        return $http({
          url: 'get_tweets.php',
          method: 'GET'
        })
      }
    }
  }
]);

App controller

app.controller("testCtrl", ["$routeParams", "truncateFilter","socialMedia", function ($routeParams, socialMedia) {

    testCtrl = this;
    this.twitterPosts = [];
    this.flickrPosts = [];
    this.loading = true;

    socialMedia.fetchTwitter().success(function(data){
        console.log(data)
        for(var i = 0; i < data.length; i++){
            testCtrl.twitterPosts.push(data[i]);
        }        
    })
    .error(function () {
        test.loading = false;
        test.error = true;
    });

     //call to get the data from Flickr
    socialMedia.fetchFlickr().success(function (data) {
        var x = data.items.length;
        for(var i = 0; i < x; i++){
            test.flickrPosts.push(data.items[i]);
        }
        test.loading = false;
    })
    .error(function () {
        test.loading = false;
        test.error = true;
    });
}]);
  • Check that you're not calling the controller twice. Btw, if you use `ui-router`, those services can be [resolved](https://github.com/angular-ui/ui-router/wiki#resolve). – soyuka May 30 '16 at 16:07
  • 3
    Possible duplicate of [Combating AngularJS executing controller twice](http://stackoverflow.com/questions/15535336/combating-angularjs-executing-controller-twice) – soyuka May 30 '16 at 16:07
  • @soyuka that was it! thanks –  May 30 '16 at 16:08

0 Answers0