我试图从控制器调用服务,这给我以下错误.. 提供商' loginService'必须从$ get factory方法返回一个值。
下面是我的代码。我做错了什么。
控制器代码
app.controller('loginController', ['$scope', '$http', 'loginService', function ($scope, $http, loginService) {
$scope.checkdata = function () {
var userName = $scope.username;
var password = $scope.password;
//Call the login service
loginService.validateUser(userName, password);
alert(response.data);
}
}])
服务代码
app.factory('loginService', function ($http) {
this.validateUser = function (userName, password) {
var userData = new Object();
userData.userName = userName;//Data.username;
userData.password = password;//Data.password;
return $http({
url: "http://localhost:53181/api/User",
dataType: 'json',
method: 'POST',
data: userData,
headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
alert(response);
if (response.data && response.data.data && response.data.data.length == 1)
return response.data.data[0];
});
}
});
答案 0 :(得分:1)
Create service funtcion like this:
yourAPICallingFuntion: function() {
var url = "your url";
var deferred = $q.defer();
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function(data) {
deferred.resolve(data.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
In Controller Call like this:
loginService.yourAPICallingFuntion().then(function(data){
//Now this will give you response in form of data
//you can this data according to your requirement
});
答案 1 :(得分:0)
factory
服务预计会从工厂函数返回一个值。它没有this
上下文(它是window
或undefined
)。
如果您想使用this
之类的this.validateUser = ...
,请改用service
服务。