如何创建自定义服务?

时间:2016-12-01 14:13:59

标签: javascript angularjs

我的控制器:

app.controller('myCtrl', function($scope, $http, $timeout) {
$scope.getData = function() {
    $http.get("../send")
        .then(function(response) {
                $scope.text = response.data;
                $scope.params = $scope.text.split(' ');
                $scope.timeFunc();
            },
            function(response) {
                $scope.timeFunc();
            });
};
$scope.timeFunc = function() {
    $timeout(function() {
        $scope.getData();
    }, 1000);
};

$scope.getData();

});

如何做到这一点,而不是在控制器中,它是一个单独的服务? 问题是变量params应该每秒更新

1 个答案:

答案 0 :(得分:0)

app.controller('myCtrl', function ($scope, $http, $timeout, servicenName) {
	$scope.getData = function () {
		servicenName.getData().then(function (response) {
			$scope.text = response.data;
			$scope.params = $scope.text.split(' ');
			$scope.timeFunc();
		},
			function (response) {
			$scope.timeFunc();
		});
	};

	$scope.timeFunc = function () {
		$timeout(function () {
			$scope.getData();
		}, 1000);
	};
	$scope.getData();
});
app.service('servicenName', function ($http) {
	this.getData = function () {
		return $http.get("../send");
	};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>