Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular自定义service服务详解 #24

Closed
Wscats opened this issue May 24, 2016 · 2 comments
Closed

Angular自定义service服务详解 #24

Wscats opened this issue May 24, 2016 · 2 comments
Labels

Comments

@Wscats
Copy link
Owner

Wscats commented May 24, 2016

在这一部分我想详细的叙述service服务在Angular中的应用
其实Angular自带很多的服务,可能你会好奇的问我服务是指什么,其实服务就是函数或者对象
根据官方的文档,Angular内部自建了超过30个服务
包括常用的$http和$location这两个服务
$http服务常用于给服务器发送请求,并响应服务器传过来的数据(其实就是提供了访问底层浏览器的XMLHttpRequest对象的方法)

var app = angular.module('wsscat', []);
app.controller('httpCtrl', function($scope, $http) {
    $http.get("wsscat.html").then(function (response) {
        $scope.data = response.data;
    });
});

$timeout就是触发我们熟悉原生Javascript的window.setTimeout函数

app.controller('timeoutCtrl', function($scope, $timeout) {
            $timeout(function() {
                $scope.content = "Angular之service详解";
            }, 1000);
        })

$interval相应也就是触发我们熟悉原生Javascript的window.interval函数

app.controller('intervalCtrl', function($scope, $interval) {
            $scope.time = new Date().toLocaleTimeString();
            $interval(function() {
                $scope.time = new Date().toLocaleTimeString();
            }, 1000);
        })

上面这三个就是我们Angular常用到的服务,只要在使用的时候注入到需要此服务中的controller中就可以获取相应的服务方法
但是我们这里是要讲的是自定义service服务,所以我们重点来说说当我们需要自己建立一个服务时候,我们该怎么做
写个简单的例子

var app = angular.module('wsscat', []);
        app.controller('serviceCtrl', function($scope, hexafy) {
            $scope.test = "Angular之service";
            $scope.hex = hexafy.myFunc(255);
        })
        app.service('hexafy', function() {
            this.myFunc = function(x) {
                return x.toString(16);
            }
        });

这里是使用自定义的的服务hexafy将一个数字转换为16进制数
这个对象是在创建应用实例的时候创建的(记住,这个对象是单例对象)
也就是说我们第一次使用这个service时候才会实例化,以后再使用的时候返回的都是同一个对象

@Wscats Wscats added the notes label Jun 3, 2016
@ziyanwould
Copy link

O(∩_∩)O好的

@qq452261789
Copy link

收到

@Wscats Wscats closed this as completed Aug 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants