plunkr:(在OP的請求代替真實API鏈路)
HTML:
<div ng-app="myApp">
<div ng-controller="myAppCtrl">
<ul>
<li ng-repeat="product in data.products" ng-bind="product.name"></li>
</ul>
</div>
</div>
的Javascript:
angular.module("myApp", [])
.constant("dataUrl", "https://some-link.com")
.controller('myAppCtrl', function($scope, corsService) {
$scope.data = {};
corsService.getData().then(function(data) {
$scope.data.products = data;
}).catch(function(error) {
$scope.data.error = error;
});
});
angular.module("myApp")
.factory('corsService', function($http, dataUrl) {
return {
getData: getData
}
function corsRequestEnabler() {
//Enable CORS requests
};
function getData() {
corsRequestEnabler();
return $http.get(dataUrl)
.then(function(response) {
console.log('Response', response);
return response.data;
}, function(error) {
return error
})
}
});
我只需要將該功能移動到服務或工廠。該功能現在正常工作,但太亂了。 –
@DanRomulus所以將它移入'myAppFactory'而不是'myHttpFn'? –
http://pastie.org/10929423我做錯了:Error:[$ injector:unpr]未知提供者:corsServiceProvider < - corsService < - myAppCtrl。所以它一定是我注入服務的方式。 –