我是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 factory方法返回一个值。”
请帮帮我。我真的很感激
答案 0 :(得分: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
})
})