【问题标题】:Using $resource and creating a POST request?使用 $resource 并创建 POST 请求?
【发布时间】:2016-02-22 03:03:16
【问题描述】:

我一直在研究这个,但无法弄清楚这个,这是我所做的简单尝试,我认为这很好,但它似乎仍然要求 get....

this.request = function(url, requestData) {
    return $resource(url, null, {
        post : {
            method : 'POST',
            params : requestData || {}
        }
    });
};

使用它:

this.request('/some/api/url', {data : true}).post();

我似乎无法弄清楚如何取回一个承诺对象,以便我可以使用响应数据....

【问题讨论】:

    标签: angularjs api post request angular-resource


    【解决方案1】:

    你想像这样创建你的资源:

    $resource(url, null, {
        post: {
            method: 'POST'
        }
    });
    

    然后:

    this.request.post(
        requestData,
        function (successResponse) {
            // Do whatever with response
        },
        function (failResponse) {
            // Do whatever with response
        }
    );
    

    这将向url 发送一个以requestData 为主体的POST 请求。

    【讨论】:

    • 我确实看到了 save 方法,但是我觉得它有点倒退,说我们有一个通过 id 获取用户的 api 调用,所以 url 类似于/users/1123123 然后是请求类似于this.request('/users/123123').save({}, function() { });
    • 我只是不想调用 save 方法,这在技术上我使用 post 方法获取数据时没有任何意义
    • 我已经更新了我的答案,以便您可以使用.post() 发帖。
    • 使用这个完全相同的解决方案,它仍然使用 GET 请求.. gahhh
    • 我刚刚也尝试过使用默认保存,但也只使用了 GET....
    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2022-11-17
    • 2020-08-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    相关资源
    最近更新 更多