2

I'm a code newbie and trying to learn angularjs. My project is simple: get JSON data from an API and display it on a web page. I found functions to make the http request and then use the data:

 app.factory('myService', function($http) {
   var myService = {
     async: function() {
       var promise = $http.get('<URL to api>').then(function(response) {
         console.log(response);
         return response.data;
       });
       return promise;
     }
   };

   return myService;
 });

 app.controller('getRealTimeBusDataCtrl', function(myService, $scope) {

   myService.async().then(function(d) {
     $scope.data = d;
   });
 });

I can then access and display the whole JSON data chunk or parts of it.

What I'd like to do is set multiple $scope variables instead of just one, but as soon as I try that, the code breaks.

What I'm trying to do:

if (d.ResponseData.Buses[1].JourneyDirection = 1) {
  $scope.timeToSollentuna = d.ResponseData.Buses[1].DisplayTime;
  else if (d.ResponseData.Buses[1].JourneyDirection = 2) {
    $scope.timeToVallingby = d.ResponseData.Buses[1].DisplayTime;
  } else if (d.ResponseData.Buses[2].JourneyDirection = 1) {
    $scope.timeToSollentuna = d.ResponseData.Buses[2].DisplayTime;
  } else {
    $scope.timeToVallingby = d.ResponseData.Buses[2].DisplayTime;
  }
}

I'm guessing the problem is how the function is set up: that it somehow limits the number of variables I can set or the number of things I can "do" after .then, but I haven't been able to figure out another way to do it.

Sorry if the answer to this question is SO obvious, but I've really tried to find it and failed.

Best regards,

0xdw
  • 3,755
  • 2
  • 25
  • 40

1 Answers1

0

The way that service is written is unnecessarily verbose. Instead, I would rewrite it like this (especially if you're starting out and learning the basics--it's good to learn good habits when starting).

app.factory('myService', ["$http", function($http){
    return {
        getData: function() {
            return $http.get('path/to/api');
        }
    };
}]);

app.controller('MainCtrl', ["$scope", "myService", function($scope, myService) {
    //declare your data model first
    $scope.busData = undefined;

    //use the service to get data
    myService.getData().then(function(response) {
        //success... got a response
        //this is where you can apply your data
        $scope.busData = response.data;

        //call a function to apply if you'd like
        applyBusData(response.data);
    }).catch(function(response) {
        //error has occurred
    });

    function applyBusData(data) {
        if(data.Buses[1].JourneyDirection === 1) {
            //etcc... etc...
        } else {
            //etc.. etc...
        }
    }
}]);
Kyle
  • 5,407
  • 6
  • 32
  • 47