【问题标题】:AngularJS - $resource different URL for Get and PostAngularJS - $resource 获取和发布的不同 URL
【发布时间】:2016-02-18 04:15:25
【问题描述】:

$resource 非常棒,它提供了非常方便的方式来处理 Web 服务。 如果 GET 和 POST 必须在不同的 URL 上执行怎么办?

例如,GET URL 是http://localhost/pleaseGethere/:id POST URL 是http://localhost/pleasePosthere,不带任何参数

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    使用 [actions] 的 'url' 属性覆盖默认 url。

    $resource(url, [paramDefaults], [actions], options);
    

    例如:

    $resource('http://localhost/pleaseGethere/:id',{},{
        getMethod:{
            method:'GET',
            isArray:true
        }
        postMethod:{
            url:'http://localhost/pleasePosthere',
            method:'POST',
            isArray:false
        }
    }
    

    Angular $resource 的使用:http://docs.angularjs.org/api/ngResource/service/$resource

    【讨论】:

    • "base" url 中使用的 :id 在 postMethod url 中也可用。 +1!
    【解决方案2】:

    您应该能够将 URL 作为参数公开。我能够做到这一点:

    $provide.factory('twitterResource', [
        '$resource',
        function($resource) {
            return $resource(
                'https://:url/:action',
                {
                    url: 'search.twitter.com',
                    action: 'search.json',
                    q: '#ThingsYouSayToYourBestFriend',
                    callback: 'JSON_CALLBACK'
                },
                {
                    get: {
                        method: 'JSONP'
                    }
                }
            );
        }
    ]);
    

    然后您可以覆盖您的 GET 调用中的 URL。

    我在非常简短的测试中发现的一个警告是,如果我在 URL 字符串中包含 http://,它就不起作用。我没有收到错误消息。它什么也没做。

    【讨论】:

    • 问题是 url 参数被编码,这就是为什么 'http://' 或任何带有 '/' 的东西都会失败。有什么想法吗?
    • 这个答案对于提问者的要求来说有点过于复杂了——Iris 的答案很中肯。
    【解决方案3】:

    如果您将带有参数名称的哈希添加到 $resource 调用中:

    $resource('localhost/pleaseGethere/:id', {id: '@id'});
    

    然后 :id 将在调用函数时映射到 id 参数(这将调用 GET localhost/pleaseGethere/123):

    Resource.get({id: 123});
    

    对于 POST,您只需不分配 id 参数:

    Resource.post({}, {name: "Joe"});
    

    将调用正确的 URL,在本例中为 POST localhost/pleaseGethere(尾部斜杠被 ngResource 剥离)。

    请参阅http://docs.angularjs.org/api/ngResource.$resource -> 示例 -> 信用卡资源了解更多详情。

    【讨论】:

      【解决方案4】:

      除了 Iris Wong 的回答之外,我想举一个具有多个方法和动作的多个参数的示例:

      angular
        .module('thingApp')
        .factory('ThingResource', ['$resource', '$state',  returnThing]);
      

      还有资源:

      function returnThing($resource, $state) {
        var mainUrl = '/api/stuffs/:stuffId/thing'
        var params = {stuffId: '@_id', thingMongoId: '@_id', thingNumber: '@_id'}
        return $resource(mainUrl, params, {
          'save': {
            url: '/api/stuffs/:stuffId/thing/:thingMongoId',
            method: 'POST',
            interceptor: {
              responseError: function(e) {
                console.warn('Problem making request to backend: ', e)
                $state.go('oops')
              }
            }
          },
          'get': {
            url: '/api/stuffs/:stuffId/thing/:thingMongoId',
            method: 'GET',
            interceptor: {
              responseError: function(e) {
                console.warn('Problem making request to backend: ', e)
                $state.go('oops')
              }
            }
          },
          'assignThing':{
            method: 'POST',
            url: '/api/stuffs/:stuffId/thing/assign/:thingNumber'
          }
        });
      }
      

      这提供了 3 种不同的方法:

      // POST to http://currnt_base_url/api/stuffs/:stuffId/thing/:thingMongoId
      ThingResource.save({
          stuffId:'56c3d1c47fe68be29e0f7652', 
          thingMongoId: '56c3d1c47fe6agwbe29e0f11111'})
      
      // GET to current http://currnt_base_url/api/stuffs/:stuffId/thing/:thingMongoId
      ThingResource.get({
          stuffId:'56c3d1c47fe68be29e0f7652', 
          thingMongoId: '56c3d1c47fe6agwbe29e0f11111'})
      
      // POST to http://currnt_base_url/api/stuffs/:stuffId/thing/assign/:thingNumber
      ThingResource.assignThing({
          stuffId:'56c3d1c47fe68be29e0f7652', 
          thingNumber: '999998'})
      

      【讨论】:

      • 全面而有价值。 +1
      【解决方案5】:

      沿着这条路走:

      (function () {
          'use strict';
      
          angular
              .module("app")
              .factory("SomeFactory", SomeFactory);
      
          function SomeFactory($resource) {
              var provider = "http://stackoverflow.com/:action/:id";
              var params = {"id":"@id"};
              var actions = {
                  "create":   {"method": "POST",  "params": {"action": "CreateAwesomePost"}},
                  "read":     {"method": "POST",  "params": {"action": "ReadSomethingInteresting"}},
                  "update":   {"method": "POST",  "params": {"action": "UpdateSomePost"}},
                  "delete":   {"method": "GET",   "params": {"action": "DeleteJustForFun"}}
              };
      
              return $resource(provider, params, actions);
          }
      })();
      

      希望对你有帮助!享受吧!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多