Wscats / articles

🔖My Learning Notes and Memories - 分享我的学习片段和与你的回忆

Home Page:https://github.com/Wscats/articles

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Angular自定义service服务详解

Wscats opened this issue · comments

在这一部分我想详细的叙述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时候才会实例化,以后再使用的时候返回的都是同一个对象

O(∩_∩)O好的

收到