【问题标题】:angularjs Factory error for ReST callReST调用的angularjs工厂错误
【发布时间】:2017-03-08 19:49:48
【问题描述】:

我是 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>

我正在尝试返回工厂,但它仍然说“Provider 'myFactory' must return a value from $get factory method.”

请帮帮我。我会很感激的

【问题讨论】:

    标签: angularjs ngresource angular-factory


    【解决方案1】:

    试试这个:

    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
        })
    }) 
    

    【讨论】:

    • 此代码有效,您的网址可能有问题。通过类似的工厂,我收到了 json 对象并在不同的控制器中获取数据。
    • 或者你可以告诉我你的错误信息以获得更多帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    相关资源
    最近更新 更多