0

Below is my angular app.

(function () {
  "use strict";

angular
    .module("app.core", ['ngRoute'])
     .controller("dataCtrl", dataCtrl);

dataCtrl.$inject = ['$scope','$location','dataService'];

/* @ngInject */
function dataCtrl($scope, $location, dataService) {
    var methods = {
        'Get': GetCustomers,
    }
    return methods.Get();

    function GetCustomers(id) {
        alert('test');
        var scarData = dataService.read(id, "").then(function (data, err) {
           console.log(data);
        });
    }
}

}());

Service

(function () {

'use strict';

angular
    .module('app.service')
    .factory('dataService', dataService);

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

function dataService($http, $q) {

    var service = {
        create: create,
        read: read,
        update: update,
        remove: remove
    }

    return service;

    function read(id,type) {
        return
        $http.get("APIURL")
        .then(success)
        .catch(exception);

        function success(response) {

        }

        function exception(ex) {

        }

    }

  function create() {} 
  function update() {}
  function detete() {}

 }
})`

While calling the service from the controller I am getting the below error.

TypeError: Cannot read property 'then' of undefined

Also, please suggest better way to call controller's get function on page load.

Kgn-web
  • 5,443
  • 13
  • 63
  • 119

1 Answers1

3

Your problem is due to Automatic Semicolon Insertion causing your return statement to end earlier than you expect.

Due to ASI, this:

    return
    $http.get("APIURL")
    .then(success)
    .catch(exception);

Is evaluated as if it had been written as:

    return;
    $http.get("APIURL")
    .then(success)
    .catch(exception);

Notice you have an empty return followed by your $http call. As a result your service method returns undefined, and your $http call never actually takes place.

The solution is to not add a line-break between the return and the $http

    return $http.get("APIURL")
        .then(success)
        .catch(exception);
kicken
  • 1,868
  • 11
  • 15
  • But now in the response, `I am getting error Uncaught SyntaxError: Unexpected token :` – Kgn-web Jun 22 '17 at 18:54
  • Please note as its was CORS request, I need to use jsonp instead of get – Kgn-web Jun 22 '17 at 18:55
  • Can you please check the snippet & tell me the better/right to call dataCtrl.Get() – Kgn-web Jun 22 '17 at 19:23
  • I don't see any reason to setup your controller like you did in the code sample. Just make the body of your GetCustomers() function the body of your controller instead and remove the fluff. – kicken Jun 22 '17 at 21:51