0

AngularJS:1.4.X
方案1:工作正常
方案2:拋出線xhr.send 404錯誤(isUndefined(後)零:柱);在angular.js休息web服務調用在AngularJS(許諾)

我想添加內置的角度緩存到我們現有的應用程序,正如我在場景1中提到的,我們在工廠'restFactory'中使用其餘調用,並將工廠注入到控制器'bookController',承諾是解決和數據加載罰款。

廠:restFactory

(function() { 
    "use strict"; 
    angular.module('myApp').factory("restFactory",['$http','confi', function($http,config){ 

    function getBooks(){ 
     return $http.get(config.serverName+"bookshelf/rest/books/data/geRestBooks"); 
    } 
    return { 
     getBooks : getBooks 
    }; 
}]); 
})(); 

控制器:BookController的

$scope.getComicbooks = function() { 
     restFactory.getBooks().then(function(response) {   
      $scope.names = response.data; 
     }, function(error) { 
      $scope.error = error; 
      $scope.names = []; 
     }); 
    }; 

現在,在方案2中,我改變了廠家的服務電話與更多的細節提出異議。但我從控制器獲得異常,而解決的承諾(我只添加了改變的代碼)

function getBooks(){ 
    return $http.get({ 
    cache: true, 
    method: 'GET', 
    url : config.serverName+"bookshelf/rest/books/data/geRestBooks" 
    }); 
} 

錯誤:angular.js:10765 GET http://127.0.0.1:53814/views/[object%20Object] 404(未找到)

網絡選項卡:
enter image description here 在場景#1,這將是一個方法調用getBooks

+1

你在哪裏打電話http://127.0.0.1:53814/views/? –

+0

@AdamWolski:我在視圖目錄下的索引頁中使用'bookController',但是當我添加console.log時,它會在它解析restFactory.getBooks()。之前中斷。然後(function(response){'。 –

+0

你在網絡標籤中看到了這個請求嗎? –

回答

3

如果你要指定方法,那麼你應該只使用$http構造方法,而不是get方法。

而不是

function getBooks(){ 
    return $http.get({ 
     cache: true, 
     method: 'GET', 
     url : config.serverName+"bookshelf/rest/books/data/geRestBooks" 
    }); 
} 

嘗試

function getBooks(){ 
    return $http({ 
     cache: true, 
     method: 'GET', 
     url : config.serverName+"bookshelf/rest/books/data/geRestBooks" 
    }); 
} 
+1

優秀的catch!OP代碼失敗的原因是因爲['http.get'](https://docs.angularjs.org/api/ng/service/$ http#get)期望第一個參數是一個URL字符串。由於OP傳遞一個對象,他們得到一個對象的字符串版本,即'[object Object]' – Phil

+2

或者,OP可以使用'$ http.get(config.serverName +「bookshelf/rest/books/data/geRestBooks」, {cache:true})' – Phil

+0

@Phil - 我實際上更喜歡你的建議,並且會提及它,但我認爲我應該堅持幫助解決這個問題,因爲之前我已經因爲建議替代品而受到懲罰。 – GPicazo