Question

I've created a web application using the Hot Towel Angular template, and I want to add a service function to the 'datacontext'.

Code is:

(function () {
    'use strict';

    var serviceId = 'datacontext';
    angular.module('app').factory(serviceId, ['common', '$http', datacontext]);

    function datacontext(common, $http) {
        var $q = common.$q;

        var service = {
            getFunctions: getFunctions
        };

        return service;

        function getFunctions() {
            var f = [];
            $http({
                method: 'GET',
                url: 'https://api.github.com/users/google/repos',
                contentType: 'application/json; charset=utf-8'
            })
            .success(function (data, status, headers, config) {
                f = data;
                console.log('f=*' + f + '*');
            })
            .error(function (data, status, headers, config) {
                alert('error!');
            });

            return $q.when(f);
        }
    }
})();


I see that the console shows some objects:

f=*[object Object],[object Object],[object O...

But when using this in my functionController.js file :

function getFunctions() {
  return datacontext.getFunctions().then(function (data) {
    console.log('data=*' + data + '*');
    return vm.functions = data;
  });
}

The value for data is set to undefined.

I'm missing something, please help identify the error.

Was it helpful?

Solution

Solution:

The getFunctions function in the datacontext should return the $http promise object, like this:

function getFunctions() {
  return $http.get('https://api.github.com/users/google/repos')
    .error(function (data, status, headers, config) {
      alert('error ! : ' + status);
  });
}


And in the controller, you can use the returned json object as follows:

function getRepos() {
  return datacontext.getRepos().then(function (httpResult) {
    vm.repos = httpResult.data;
  });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top