2015-08-22 63 views
0

我想從文件driverStandings.json(您可以在圖像的結構中看到它)中加載json。我使用服務API來加載這些數據。我使用下面的代碼(在圖像中)。AngularJS從services.js文件中加載json

Left the project sturcture, right the service class

當我編譯,我沒有得到我的驅動列表,我獲得以下錯誤列表

TypeError: url.replace is not a function 
    at angular.js:8557 
    at sendReq (angular.js:8426) 
    at $get.serverRequest (angular.js:8146) 
    at deferred.promise.then.wrappedCallback (angular.js:11682) 
    at deferred.promise.then.wrappedCallback (angular.js:11682) 
    at angular.js:11768 
    at Scope.$get.Scope.$eval (angular.js:12811) 
    at Scope.$get.Scope.$digest (angular.js:12623) 
    at Scope.$get.Scope.$apply (angular.js:12915) 
    at done (angular.js:8450) 

什麼是類型錯誤和我究竟做錯了什麼?

+0

請張貼直播代碼不是圖像。使複製非常難以幫助創建答案 – charlietfl

回答

1

你不想使用jsonp的方法靜態JSON資源和你嵌套另一個$http調用作爲URL到外部的

只需使用內部$ http和擺脫外的人的

FAPI.getDrivers = function(id){ 
    return $http.get(... path to json file ...) 
} 
+0

您的意思是:F1API.getDrivers = function(){ return $ http.get('/ app/data/driverStandings.json'); } ?? – Jonas

+0

是的......正是我的意思 – charlietfl

+0

去試試這個(下次我添加代碼手冊)。 – Jonas

0

正如你在documentation中看到的那樣,url需要一個帶有正確url的字符串,只要從那裏除去$ http.get並且它應該可以工作,但是首先看看doc。

1
angular 
    .module('FomulaOne.services', {}) 
    .factory('F1APIService', function ($http) 
     { 
      function http_get (url, doneFunc, failFunc) 
      { 
       var promise = $http.get(url); 

       promise.success(doneFunc); 

       if (failFunc) // optional error catch 
        promise.error(failFunc); 

       return promise; 
      } 

      return { 
       getDrivers: function (doneFunc, failFunc) 
       { 
        return http_get('/app/data/driversStandings.json', doneFunc, failFunc); 
       }, 
       getDriverDetails: function (id, doneFunc, failFunc) 
       { 
        return http_get('/app/data/' + id + '/driversStandings.json', doneFunc, failFunc); 
       }, 
       getDriverRaces: function (id, doneFunc, failFunc) 
       { 
        return http_get('/app/data/' + id + '/results.json', doneFunc, failFunc); 
       } 
      }; 
     }); 

要使用

F1APIService.getDriverDetails(
    123, 
    function (response) 
    { 
     // Do stuff on success 
    }, 
    function (response) 
    { 
     // Do stuff on error 
    } 
);