离子http.get在工厂不起作用

时间:2015-11-05 22:00:08

标签: angularjs ionic-framework

所以如果我在控制器中执行此操作,我可以从URL获取数据。但是,如果我把它带到工厂,它就行不通。我做错了什么?

angular.module('starter.notifications', [])

.factory('Notifications', function($http) {
  var link = "http://localhost:8000/notifications";
  var notifications = [];
  return {
    getAll: function()
    {
      return $http.get(link).success(function(data, status, headers, config) {
          notifications = data;
          return notifications;          
      });

    },

如果我将它移动到控制器中,此代码可以工作,但为什么它不能在工厂中运行?

2 个答案:

答案 0 :(得分:0)

这就是我做到的。

在app.js的顶部

angular.module('app', ['ionic', 'app.controllers', 'app.services','ngCordova'])

让离子通过声明知道你有一个services.js。

services.js(http post请求示例)

    angular.module('app.services', ['ngCordova'])

.factory('dataFactory', function($http, $cordovaGeolocation){

    var dataFactory = {};


    dataFactory.login = function(username, password){

        var config = {

            headers:  {

                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
        var data = 'userID=' + username + '&password=' + password +'';
        var httpAddressDoLogin = "http://YOURURL";
    return $http.post(httpAddressDoLogin, data, config);

    };

    return dataFactory;


})

在您的控制器中:

dataFactory.login(username, password).then(function(resp) {

希望有所帮助。

答案 1 :(得分:0)

在services.js $ http.get上生成promise而不是object数组。要使其工作在您的services.js

上这样写
angular.module('starter.services', [])
.factory('Actor', function($http) {
var actors = $http.get('http://ringkes/slim/snippets/actor').then(function(resp) {
if (resp) { 
return = resp['data'];// This will produce promise, not array so can't call directly
} else {
console.error('ERR', err);
}
});
return {
all: function() {
  return actors;
}
};
});

然后在控制器上调用它:

controller('DashCtrl', function($scope,Actor,$http) {
Actor.all().then(function(actors){ $scope.actors = Actor.all();
});
});
相关问题