2017-06-22 97 views
0

下面是我的角度應用程序。TypeError:無法讀取未定義的屬性'then'#2

(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); 
     }); 
    } 
} 

}()); 

服務

(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() {} 

} 
})` 

雖然調用來自控制器的服務我得到下面的錯誤。

TypeError: Cannot read property 'then' of undefined

此外,請在頁面加載時建議更好的方式來調用控制器的get函數。

+0

移動'success'和返回語句之前'exception'功能之間添加一個換行符。 – Hoyen

回答

3

您的問題是由於Automatic Semicolon Insertion導致您的return語句比您預期的更早結束。

由於ASI,這樣的:

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

,就好像它已經被寫成評價:

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

通知你有一個空的回報,然後你的$ HTTP調用。因此,您的服務方法返回未定義,並且您的$ http調用從未實際發生。

的解決方案是不返回和$ HTTP

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

是的,你是對的。謝謝 –

+0

但現在在響應中,'我得到錯誤未捕獲SyntaxError:意外的令牌:' –

+0

請注意,因爲它是CORS的請求,我需要使用jsonp而不是得到 –

相關問題