0

我是 AngularJs 的新手,我正在尝试用 ngResource 编写一个工厂来进行 Rest 调用

这是我的代码

工厂

'use strict';

angular.module('restPracticeApp')
  .factory('myFactory',['$resource', function () {


    console.log('hi from factory')
  function myFactory($resource) {
    var myUrl = 'api/theUrl';

  return $resource(myUrl,{} , {
      'query': { method: 'GET', isArray: true},
      'get': { method: 'GET'}
        });  

  }
  }]);

控制器 :

'use strict';


angular.module('restPracticeApp')
  .controller('AboutCtrl',['$scope','$resource','$http','myFactory' ,
    function ($scope,$resource,$http,myFactory) {

        $scope.theLink = theLink;

        function theLink(theName) {
            $http({
                    method: 'GET',
                    url: "http://localhost:9000/api/theUrl",
                    data: $scope.theName
            })
            .then(
                function successCallback(response) {

                    console.log(response);
                    $scope.result=response;
                },
                function errorCallback(response) {

                    console.log(response);
                    $scope.result=response;
              });
        }
  }]);

并在 HTML

<input type="text" ng-model="theName">
<button class="btn btn-block" ng-click="theLink(theName)">yo</button>

我正在尝试返回工厂,但它仍然说“提供者'myFactory'必须从 $get 工厂方法返回一个值。”

请帮帮我。我会很感激

4

1 回答 1

0

试试这个:

factory("myFactory",function($resource){
    var factory = {};
    factory.getResources = $resource('api/theUrl', {}, {
        'query': {method: 'GET', isArray: true}
    });
    return factory;
})

关于如何接收工厂数据的控制器示例:

.controller("AboutCtrl",function($scope,$resource,$http,myFactory){

    $scope.factorydata = myFactory.getResources.query();
    $scope.factorydata.$promise.then(function(data) {
        //something you want to do
    })
}) 
于 2017-03-08T20:13:23.500 回答