2017-05-03 52 views
0

我有一個Api,其中檢索自定義標題:X-Total-Count:「項目總數」,我使用的角度爲ngResource使用ngResource訪問標題

我廠是這樣的:

app.factory("shopFactory", function ($resource) { 
    return { 
     User: $resource("http://localhost:58495/users/api/User/?id=:id", { id: "@id" }), 
     Category: $resource("http://localhost:58495/category/:id", { id: "@id" }), 
     Product: $resource("http://localhost:58495/products/?from=:from&to=:to", { from: "@from", to: "@to" }) 
    }; 
}); 

當我把它叫做:

var productServer = shopFactory.Product.query({ from: 0, to: 10 }).$promise.then(function (response) { 
     $scope.product = response; 
     console.log(response); 
    }, function (error) { 
     console.log("ERROR"); 
     console.log(error); 
    }); 

我怎樣才能通過ngResource訪問我的自定義標題,我可以,但用$訪問HTTP,我想用$ resource的方式做,謝謝

回答

0

可以用三個參數調用query動作方法:

Resource.query([parameters], [success], [error]) 

使用(value (Object|Array), responseHeaders (Function), status (number), statusText (string))參數調用成功回調函數,其中值是填充的資源實例或集合對象。使用(httpResponse)參數調用錯誤回調。

var productServer = shopFactory.Product.query(
    { from: 0, to: 10 }, 
    function success (value, headers, status, statusText) { 
     $scope.product = value; 
     console.log(value); 
     console.log(headers()); 
    }, 
    function error (error) { 
     console.log("ERROR"); 
     console.log(error); 
    } 
); 

欲瞭解更多信息,請參閱AngularJS $resource Service API Reference


最新使用$promise.then和成功函數之間的差,

.then方法的功能僅僅暴露的最終響應的value。成功回調暴露了四個參數:value (Object|Array), responseHeaders (Function), status (number), statusText (string)

$promise可以作爲參數傳遞給其他函數,其方法可以多次調用。

另一個非常重要的區別是.then方法根據返回的值創建了一個新的承諾。

鏈接承諾

,因爲調用一個承諾的.then方法返回一個新派生的承諾,這是很容易可以創建承諾的一個鏈條。

它可以創建任何長度的鏈,並且自一個承諾可以與另一個承諾(這將進一步推遲其分辨率)來解決,所以能夠暫停/在任何點推遲的承諾的決議鏈。這使得實現強大的API成爲可能。

— AngularJS $q Service API Reference (Chaining Promises)

+0

謝謝,它的工作完美無缺。我只有一個問題,使用$ promise.then和成功函數有什麼區別,非常感謝。 –