0
嘗試使用Angular資源從API中下拉項目列表。如果我從瀏覽器中打開並使用swagger,api會起作用,我會得到一個json項目列表。查詢錯誤翻譯的角度資源返回列表
但是無法通過角度過去的錯誤輸出頁面上的結果列表。
.factory('ProjectsDS', ['$resource','$timeout',
function($resource, $timeout){console.log(0);
var proj = $resource('/projects');
$timeout(2000);
console.log(0 + ' ' + proj.query().length);
return $resource('/projects')}])
錯誤在瀏覽器控制檯:
"Error: [$resource:badcfg] http://errors.angularjs.org/1.5.5/$resource/badcfg?p0=Error%20in%20resource%20configuration%20for%20action%20%60%7B0%7D%60.%20Expected%20response%20to%20contain%20an%20%7B1%7D%20but%20got%20an%20%7B2%7D%20(Request%3A%20%7B3%7D%20%7B4%7D)&p1=query&p2=array&p3=object&p4=GET&p5=%2Fprojects
O/<@http://localhost:8000/js/angular.min.js:6:412
resourceFactory/</Resource[name]/promise<@http://localhost:8000/js/angular-resource.js:682:25
e/<@http://localhost:8000/js/angular.min.js:130:226
tf/this.$get</[email protected]://localhost:8000/js/angular.min.js:144:463
tf/this.$get</[email protected]://localhost:8000/js/angular.min.js:142:39
tf/this.$get</[email protected]://localhost:8000/js/angular.min.js:145:247
[email protected]://localhost:8000/js/angular.min.js:97:53
[email protected]://localhost:8000/js/angular.min.js:101:190
dg/</[email protected]://localhost:8000/js/angular.min.js:102:229
"
使用超時處理,我認爲,最初的空返對象。長度不輸出0
API的回報,如果瀏覽到:
{"_links":{"self":{"href":"http:\/\/localhost:8000\/projects?page=1"},"first":{"href":"http:\/\/localhost:8000\/projects"},"last":{"href":"http:\/\/localhost:8000\/projects?page=1"}},"_embedded":{"projects":[{"id":"1","message":null,"timestamp":null,"user":null,"name":"First 1","site":"https:\/\/www.nathanhaley.com","description":"This is one description.","_links":{"self":{"href":"http:\/\/localhost:8000\/projects\/1"}}},{"id":"2","message":null,"timestamp":null,"user":null,"name":"First 1","site":"https:\/\/www.nathanhaley.com","description":"This is one description.","_links":{"self":{"href":"http:\/\/localhost:8000\/projects\/2"}}},{"id":"3","message":null,"timestamp":null,"user":null,"name":"First 2","site":"https:\/\/www.nathanhaley.com","description":"This is one description.","_links":{"self":{"href":"http:\/\/localhost:8000\/projects\/3"}}},{"id":"4","message":null,"timestamp":null,"user":null,"name":"First 12","site":"https:\/\/www.nathanhaley.com","description":"This is one description.","_links":{"self":{"href":"http:\/\/localhost:8000\/projects\/4"}}}]},"page_count":1,"page_size":25,"total_items":4,"page":1}
感謝您的幫助。
感謝,但同時控制檯顯示[對象的對象],如果我走長度斷爲產生未定義,因爲不proj.get()[0 ]。所以它對我來說似乎是一個空洞的對象,或者我該如何檢查。如果我只是運行proj.query(),我會得到一個像Array一樣的控制檯的空數組。 – Geodin
我忘了 - $資源返回一個承諾。要訪問從API返回的數據,需要解決承諾。試試'proj.get()。$ promise.then(function(result){console.log(result)})'。順便說一句,你是否普遍熟悉承諾/異步函數?我對自己承諾相對較新。當我第一次開始使用promise時,我實現了$ resource,但是後來建議我先學習$ http。現在,我在當前項目中使用$ http,它非常簡單,適合我的需求。如果可以的話,絕對要學習$資源,但是$ http更容易以 – devthorne
開頭。另外,$ timeout不應該是必須的,因爲承諾將在數據返回時解析 – devthorne