In Angular there are several built in services. $http service is one of them. In this video, we will discuss another built in service, $log. It is also possible to create our own custom services in Angular. 

At this point several questions come to our mind

  • What are services in Angular
  • When should we be creating services in Angular
  • How to create our own custom Angular services
  • Where do they fit, in an angular application architecture
  • What are the benefits of using services

I will answer all these questions in a later video. The reason for postponing this discussion, is that, it is easier to understand the concept of Angular services and the benefits they provide, once we understand how to use use 1 or 2 built in angular services. 

So, let's start our discussion with $http service. 

$http service in Angular is used to make HTTP requests to remote server 

$http service is a function that has a single input parameter i.e a configuration object. 

Example : The following example issues a GET request to the specified URL

$http({
    method: 'GET',
    url: 'EmployeeService.asmx/GetAllEmployees'
});

In the example above we are only using 2 properties of the configuration object. Check the link below for the complete list of properties supported by the configuration object
https://docs.angularjs.org/api/ng/service/$http#usage

Shortcut methods like get, post, put, delete etc are also available to be used with $http service

Example : Using the short cut method get()
$http.get('EmployeeService.asmx/GetAllEmployees')

$http service returns a promise object. This means the functions are executed asynchronously and the data that these functions return may not be available immediately. Because of this reason you cannot use the return value of the $http service as shown below.

$scope.employees = $http.get('EmployeeService.asmx/GetAllEmployees');

Instead you will use the then() method. The successCallback function that is passed as the parameter to the then function is called when the request completes. The successCallback function receives a single object that contains several properties. Use the data property of the object to retrieve the data received from the server.

$scope.employees = $http.get('EmployeeService.asmx/GetAllEmployees')
            .then(function (response) {
                $scope.employees = response.data;
            });

You can use the $log service to log the response object to the console to inspect all of it's properties

$scope.employees = $http.get('EmployeeService.asmx/GetAllEmployees')
                        .then(function (response) {
                            $scope.employees = response.data;
                            $log.info(response);
                        });

If there is an error processing the request, the errorCallback function is called. The errorCallback function is passed as the second parameter to the then() function. The errorCallback function receives a single object that contains several properties. Use the data or statusText properties of the returned object to find the reasons for the failure.

$scope.employees = $http.get('EmployeeService.asmx/GetAllEmployee')
                        .then(function (response) {
                            $scope.employees = response.data;
                        }, function (reason) {
                            $scope.error = reason.data;
                        });

You can use the $log service to log the response object to the console to inspect all of it's properties

$scope.employees = $http.get('EmployeeService.asmx/GetAllEmployee')
                        .then(function (response) {
                            $scope.employees = response.data;
                        }, function (reason) {
                            $scope.error = reason.data;
                            $log.info(reason);
                        });

You can also create separate functions and associate them as successCallback and errorCallback functions

var successCallBack = function (response) {
    $scope.employees = response.data;
};
 
var errorCallBack = function (reason) {
    $scope.error = reason.data;
}
 
$scope.employees = $http.get('EmployeeService.asmx/GetAllEmployees')
                        .then(successCallBack, errorCallBack);

Default Transformations provided by Angular's http service

    • If the data property of the request configuration object contains a JavaScript object, it is automatically converted into JSON object
    • If JSON response is detected, it is automatically converted into a JavaScript object

Part 18 $http service in AngularJS的更多相关文章

  1. Part 17 Consuming ASP NET Web Service in AngularJS using $http

    Here is what we want to do1. Create an ASP.NET Web service. This web service retrieves the data from ...

  2. Part 20 Create custom service in AngularJS

    Whenever the case changes from lower to upper, a single space character should be inserted. This mea ...

  3. AngularJs学习笔记--Managing Service Dependencies

    原版地址:http://docs.angularjs.org/guide/dev_guide.services.managing_dependencies angular允许service将其他ser ...

  4. angularJS(6)

    angularJS(6) 一:angularJs的事件. 1.ng-click指令定义了AngularJS点击事件. <div ng-app="myapp" ng-contr ...

  5. AngularJs之五

    一:angularJs的事件. 1.ng-click指令定义了AngularJS点击事件. <div ng-app="myapp" ng-controller="m ...

  6. Angular Service入门

    1.Angular内置service Angular为了方便开发者开发,本身提供了非常多的内置服务.可以通过https://docs.angularjs.org/api/ng/service查看Ang ...

  7. 前端见微知著AngularJS备忘篇:温故而知新,可以为师矣

    话说以前JQuery刚出来的时候,真的是对个人的冲击蛮大的.记得当时我买的第一本书就是<锋利的JQuery>,藉由这本书开始,我从此以后的项目基本用上了JQuery,其给我带来的便利性是不 ...

  8. 【AngularJS学习笔记】01 指令、服务和过滤器

    AngularJS 指令是扩展的 HTML 属性,带有前缀 ng-. 比如: ng-app 指令初始化一个 AngularJS 应用程序.注意ng-app一般为空,如果值不为空,就得加这样一句代码va ...

  9. AngularJs学习笔记--Forms

    原版地址:http://code.angularjs.org/1.0.2/docs/guide/forms 控件(input.select.textarea)是用户输入数据的一种方式.Form(表单) ...

随机推荐

  1. P4643-[国家集训队]阿狸和桃子的游戏【结论】

    正题 题目链接:https://www.luogu.com.cn/problem/P4643 题目大意 给出\(n\)个点\(m\)条边的无向图,两个人轮流选择一个未被选择的点加入点集. 然后每个人的 ...

  2. 深入浅出WPF-11.Template(模板)01

    模板 在WPF中,模板可以分为两大类: 控件模板(ControlTemplate)是算法内容的表现形式,一个控件怎么组织其内部的结构才能让它更符合业务逻辑,让用户操作更舒服,都是由她控制的.它决定了控 ...

  3. 《手把手教你》系列技巧篇(二十八)-java+ selenium自动化测试-处理模态对话框弹窗(详解教程)

    1.简介 在前边的文章中窗口句柄切换宏哥介绍了switchTo方法,这篇继续介绍switchTo中关于处理alert弹窗的问题.很多时候,我们进入一个网站,就会弹窗一个alert框,有些我们直接关闭, ...

  4. 《面试八股文》之 JVM 20卷

    微信公众号:moon聊技术 关注选择" 星标 ", 重磅干货,第一 时间送达! [如果你觉得文章对你有帮助,欢迎关注,在看,点赞,转发] 大家好,我是 moon. <面试八股 ...

  5. hmac和socketserver

    一,hmac 验证客户端的合法性 hmac,检测客户端是否合法,不依赖登录认证 server import os,socket,hmac sk=socket.socket() sk.bind(('12 ...

  6. C语言对"不定长"字符串数组的遍历

    一般来说,c语言的数组的初始化可以通过三种方式: {0},在声明时使用,如 int a[10]={0} 使用memset, memset(array,0,sizeof(array)) 用for循环赋值 ...

  7. JVM:类加载与字节码技术-1

    JVM:类加载与字节码技术-1 说明:这是看了 bilibili 上 黑马程序员 的课程 JVM完整教程 后做的笔记 内容 类文件结构 字节码指令 下面的内容在后续笔记中: 编译期处理 类加载阶段 类 ...

  8. Redis的浅入门

    Redis的浅入门 # 缓存的思想 问题提出:我们的用户数量上亿,如果登录,访问数据库user特别耗时,该怎么办?--提出缓存 方法:怎样从缓存在获取数据? *有数据: 直接返回 *无数据: (1)从 ...

  9. 数列极限计算中运用皮亚诺Taylor展开巧解

    这是讲义里比较精华的几个题目,今晚翻看也是想到了,总结出来(处理k/n2形式). 推广式子如下: 例题如下:

  10. Spring MVC:HandlerMapping

    HandlerMapping 的类图 Spring中存在两种类型的handlers.第一种是 handler mappings(处理程序映射).它们的角色定位与前面所描述的功能完全相同.它们尝试将当前 ...