高效利用Angular中内置服务

Posted fareise

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了高效利用Angular中内置服务相关的知识,希望对你有一定的参考价值。

AngularJS中为我们提供了众多的内置服务,通过这些内置服务可以轻松的实现一些常用功能。下面对Angular中常用的内置服务进行一下总结。

1.$location服务

$location服务用于返回当前页面的URL地址,示例代码如下:

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});
这里为$scope对象定义了myUrl变量,然后利用$location服务读取到了URL地址并存储到myUrl中。

2..$http服务

$http 是 AngularJS 中最常用的服务,它经常用于服务器的数据传输。下面的例子中服务向服务器发送请求,应用响应服务器传送过来的数据。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});
3.$timeout()服务和$interval()服务

这两个服务的功能对应的是javascript中的setTimeout()和setTimeInterval函数。一个简单的实时更新时间例子如下:

app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});
除了Angular中提供的内置服务外,我们也可以自己定义服务,利用service即可,下面是一个定义服务的基本代码框架:

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
定义好服务后,我们可以像使用内置的Angular服务一样使用它:

app.controller('myCtrl', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(255);
});




以上是关于高效利用Angular中内置服务的主要内容,如果未能解决你的问题,请参考以下文章

Apollo Codegen 没有找到生成代码的操作或片段

json 可视代码工作室Angular with Firebase片段

typescript Angular 2测试片段。代码库https://developers.livechatinc.com/blog/category/programming/angular-2/

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

typescript Angular最终版本的Angular 2测试片段。代码库https://developers.livechatinc.com/blog/category/programming