2.3.7 AngularJS 服务service - OhNaNaSun/angularBlog GitHub Wiki
参考:权威教程
服务
服务是一个单例对象,在每个应用中只会被实例化一次(被$injector实例化),并且是延迟加载的(需要时才会被创建)。服务提供了把与特定功能相关联的方法集中在一起的接口。
创建和注册服务
AngularJS中,factory()方法是用来注册服务的最常规方式,同时还有其他一些API可以特定情况下帮助我们节省代码量。 共有5种方法用来创建服务:
- factory()
- service()
- constant():可以将一个已经存在的变量值注册为服务,并将其注入到应用的其他部分中。
- value():如果服务的$get方法返回的是一个常量,那就没必要定义一个包含复杂功能的完整服务,可以通过value()方法方便地注册服务。
- provider()
value()方法和constant()方法的最主要区别是,常量可以注册到配置函数中,而值不行。通常情况下,可以通过value()注册服务对象或函数 用constant()来配置数据。
内置服务service
$http
- $httpProvider
- service in module ng The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
binding data from $http.get() request into ng-repeat
$scope.navArr在获取数据之前必须初始化
return app.controller('LayoutController', function($scope, $http){
$http.get("/checklogin").then(function(user){
$scope.navArr = [];
if(user.name){
$scope.navArr = [
{
name: "Dashboard",
url: ""
},
{
name: "Settings",
url: ""
},
{
name: "Profile",
url: ""
},
{
name: "Help",
url: ""
}
];
}else{
console.log("not login");
$scope.navArr = [
{
name: "Log in",
url: ""
},
{
name: "Sign Up",
url: ""
}
];
}
})
})
$scope上的数据什么时候更新(脏数据检查 != 轮询检查更新)? 参考:AngularJS性能优化心得 权威指南 如果响应状态码在200和299之间,会认为响应是成功的,success回调被调用,否则error回调被调用。如果响应是重定向,error不会被调用。
$location
The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
path([path]);
This method is getter / setter.
Return path of current URL when called without any parameter.
Change path when called with parameter and return $location.
Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing.
// given URL http://example.com/#/some/path?foo=bar&baz=xoxo
var path = $location.path();
.$timeout()服务和$interval()服务
这两个服务的功能对应的是javascript中的setTimeout()和setTimeInterval函数