【问题标题】:access headers with ngResource使用 ngResource 访问标头
【发布时间】:2017-05-04 22:40:33
【问题描述】:

我有一个 Api,其中检索自定义标题:X-Total-Count:“项目总数”,我正在使用带有 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 方式,谢谢

【问题讨论】:

    标签: angularjs http-headers ngresource


    【解决方案1】:

    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 方法根据返回的值创建一个新的承诺。

    链式承诺

    因为调用 Promise 的 .then 方法会返回一个新的派生 Promise,所以很容易创建一个 Promise 链。

    可以创建任意长度的链,并且由于 可以用另一个 Promise 解决一个 Promise(这将进一步推迟其解决方案),因此可以在链中的任何点。这使得实现强大的 API 成为可能。

    — AngularJS $q Service API Reference (Chaining Promises)

    【讨论】:

    • 谢谢,它完美无缺。我只有一个问题,使用 $promise.then 和 success 函数有什么区别,非常感谢。
    猜你喜欢
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2016-04-27
    • 1970-01-01
    • 2019-10-04
    • 2023-03-06
    相关资源
    最近更新 更多