【问题标题】:How to work with $resource in angularjs如何在 angularjs 中使用 $resource
【发布时间】:2013-10-31 09:33:39
【问题描述】:

我正在尝试从这个 url http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo 获取数据

下面通过$resource是我的资源代码

angular.module('myApp.services', ['ngResource']).
 value('version', '0.1').factory('recipes1',['$resource', '$http', '$log', function  ($resource, $http, $log) {
return $resource('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo',{ },{   locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter) {
  // probably be better if you examined the results in here
alert(data);

 })}
});
}]);

但我没有得到回应。我正在从我的控制器中退出

function Resource(value){
"use strict";

    copy(value || {}, this);
  } 

【问题讨论】:

    标签: ajax json angularjs


    【解决方案1】:

    $http 与承诺工厂一起使用:

    查看 fiddle

    中的工作演示

    JS

    var fessmodule = angular.module('myModule', ['ngResource']);
    
    fessmodule.controller('fessCntrl', function ($scope, Data) {
    
        $scope.runMe = function () {
    
            Data.query($scope.url)
                            .then(function (result) {
                               $scope.data = result;
    
                            }, function (result) {
                                alert("Error: No data returned");
                            });    
        }
    
    });
    
    fessmodule.$inject = ['$scope', 'Data'];
    
    fessmodule.factory('Data', ['$http','$q',  function($http, $q) {
    
         var data = $http({method: 'GET', url: 'http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'});
    
           var factory = {
                query: function (address) { 
                    var deferred = $q.defer();              
                    deferred.resolve(data);               
                    return deferred.promise;
                }
            }
            return factory;
    }]);
    

    【讨论】:

    • 你在那个工作上工作,但我的客户需要 $resource
    • 你使用RESTful服务端数据源吗?如果不是,我建议不要使用$resource
    • 它的 json 格式你可以检查 url。我是 angularjs 和 restful 服务的初学者。
    • 在您的情况下,您使用http://api.geonames.org 站点根据提供的位置纬度/经度获取 Json。我看不出他有理由使用resource
    • 我没有,今天只使用 $http,抱歉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2015-11-02
    相关资源
    最近更新 更多