Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have the following 3 methods in my module.factory dataservice I am using Angular 1.5

  • getCannedJSON . This function works as intended and i would like the others to behave the same way. I copy and pasted the JSON i got from my webAPI in postman and put this in to the function. It returns an array of objects like i want.
  • getDataFromAPI. For some reason I cannot get this function to return the response. The console.log(response) has exactly the data I want aka the same data as getCannedJSON. Instead it returns a d {$$State: object} any idea how i could alter this code to change have it return in the same format as the getCannedJson method?
    • getDataFromApiWithDynamicUrl this is no different than the above method but it will take a dyanmic url for the web api. It workds fine minus it not returning an array list of json objects it instead returns the same $$State object.

I would like getDataFromAPI to return the same array of all the objects in the json request like getCannedJson does. Any ideas where I am messing up. Below is a screenshot of the two different types of objects they are returning via console.log I would like the data at the bottom to look like the data at the top.

enter image description here

The code for the dataService module factory is below

(function (module) {
'use strict';

DataService.$inject = ['$http', '$q'];

function DataService($http, $q) {
    var getDataFromAPI = function () {
        var returnthis; 
        return $http({ //this top level returns instead 
            url: "http://localhost:34183/api/quality/month",
            dataType: 'json',
            method: 'GET',
        }).success(function (response) {
            console.log("This Response shown below is pefect! but it wont return....");  
            console.log(response);
            return (response);//This never returns
        }).error(function(error){
            console.log(error);
        });
        return returnthis;
    };
    var getDataFromApiWithDynamicUrl = function (pathurl) { // this is version 2 of the method i want to work where i can dynamically change the url to the path
        return $http.get(pathurl);
    };
    var getCannedJSON = function ($http) {
        return [{
                  "hockeyTeam": "Sharks",
                  "PlayoffRecord": {
                      "wins": "0"
                  },
              },
              {
                  "hockeyTeam": "Pengiuns",
                  "PlayoffRecord": {
                      "wins": "1"
                  },
              }
        ];
    };
    return {
        getDataFromAPI: getDataFromAPI,
        getDataFromApiWithDynamicUrl: getDataFromApiWithDynamicUrl,
        getCannedJSON: getCannedJSON
    };
}
module.factory('DataService', DataService);
})(angular.module('MyCoolModule'));

below is the code where i call these methods to consume the JSON data in my controller.

(function (module) {
'use strict';

hockeyViewController.$inject = ['DataService'];
function hockeyViewController(DataService) {
    var vm = this;

    vm.headers = [
        { name: 'Hockey Team', key: 'hockeyTeam' },
        { name: 'Record', key: 'PlayoffRecord'}
    ];

    vm.cannedData = angular.copy(DataService.getCannedJSON());
    vm.getDataFromAPI = DataService.getDataFromAPI();
    vm.getDataFromAPIwithCustomURL = [];
    DataService.getDataFromApiWithDynamicUrl("http://localhost:34183/api/quality/month").then(function(response){
        console.log("this response should work - and it does it in the right format");
        console.log(response.data);// this looks perfect
        vm.getDataFromAPIwithCustomURL = response.data;
        return response.data;
    }, function (error) {
        console.log(error);
    });
    vm.testMonthResults2 = angular.copy(DataService.getDataFromApiWithDynamicUrl("http://localhost:34183/api/quality/month"));

    console.log("canned json Data- works great"); 
    console.log(vm.cannedData);// this works perfectly  
    console.log("this is the data results with dynamic url - returns wrong object the $$state ");
    console.log(vm.getDataFromAPI);// returns $$state not array of objects
    console.log(vm.getDataFromAPIwithCustomURL); // this returns [] which is wrong
    console.log(DataService.getDataFromApiWithDynamicUrl("http://localhost:34183/api/quality/month"));
    // this doesnt work either 
}
function reportTabularViewDirective() {
    return {
        restrict: "E",
        controller: hockeyViewController,
        controllerAs: 'vm',
        bindToController: true,
        scope: {
        },
        templateUrl: "app/widgets/hockey-view.html"
    };
}

module.directive('hockeyView', hockeyViewDirective);

})(angular.module('MyCoolModule'));

share|improve this question
    
I believe you need to defer the result: stackoverflow.com/questions/18101875/… Personally, I use the .then(...) method for all http requests, not success(...) and error(...) – Andonaeus May 31 at 19:03
    
    
i kind of understand how one should use the .then method instead of success, however i still am not implementing it correctly – ngnewb May 31 at 20:44
up vote 0 down vote accepted

Can try this one

var getDataFromAPI = function () {
        return $http({
            url: "/api/quality/month", // try using relative path
            dataType: 'json',
            method: 'GET',
           }).then(function(response) {
              console.log(response);
              return respose.data;
           }, function(error) {
              console.log(error);
              return [];
          });
 };

But better to use like: service return only promise and in controller use then function to handle response

In service:

var getDataFromAPI = function() {
     return $http.get('/api/quality/month');
};

in controller:

DataService.getDataFromAPI().then(function(response) {
    console.log(response.data);
}, function(error) {
    console.log(error);
});
share|improve this answer
    
both dont change a thing. Is it possible I am missing something. for the top example do i also need to have a .then in the controller? – ngnewb May 31 at 19:36
    
problem was you returned returnthis before get response. no need to use then for first process. however in my second process what value shown for response or error? – shaishab roy May 31 at 19:41
    
i get the same {$$state: Object}$$state: Objectstatus: 0__proto__: Object__proto__: Object someone down-voted this and the original question. I wish they would have said what didnt make sense – ngnewb May 31 at 20:13
    
do i maybe have to return something in the .then()? in the controller? – ngnewb May 31 at 20:15
    
Can you show how call from controller ? can you check pls your server side that you get call for this function and return valid information? – shaishab roy Jun 1 at 7:38

You get a $promise object by calling DataService.getDataFromAPI(). You need to handle the $promise object to get the response.

DataService.getDataFromAPI().then(function(response) {
    // console.log(response);
})

The same applies when you getDataFromApiWithDynamicUrl() function.

For more info, see doc:

$http
$q

share|improve this answer
    
It would be proper to call it $q promise object. $promise may refer to $resource promise in Angular context, it is not the case here. – estus Jun 1 at 0:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.