2015-11-05 83 views
0

所以我可以從URL中獲取數據,如果我在我的控制器中使用它。但是,如果我採取這種做法並將其移入工廠,則不起作用。那麼我做錯了什麼?離子http.get不工作在工廠

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

    }, 

這段代碼的工作原理是,如果我將它移動到控制器中,但爲什麼它不在工廠工作?

回答

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

希望有所幫助。

0

關於services.js $ http.get導致promise不是對象數組。爲了使工作寫這樣您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(); 
}); 
});