Http服务

HttpClient 是 Angular 通过 HTTP 与远程服务器通讯的机制。


启用Http服务的准备工作

要让 HttpClient 在应用中随处可用,需要在根模块的@NgModule.imports 数组中加入 HttpClientModule


Http方法返回单个值

HTTP 是一个请求/响应式协议。你发起请求,它返回单个的响应。
所有的 HttpClient 方法都会返回某个值的 RxJS Observable。
通常,Observable 可以在一段时间内返回多个值。但来自 HttpClient 的 Observable 总是发出一个值,然后结束,再也不会发出其它值

注: 可观察对象(Observable) 是声明式的,即定义的用于发布值的函数,必须由消费者订阅后,该函数才会实际执行。

使用RxJS 的 of() 函数来模拟Observable:

getHeroes(): Observable<Hero[]> {return of(HEROES);
}

HttpClient.get()方法

方法参数:

  • URL地址
  • options参数(可选)

get()方法有如下特点:

  • 构造一个GET请求,将主体解释为JSON并返回。
  • 请求参数和对应的值附加在URL后面,利用 ? 号代表URL的结尾和请求参数的开始(GET请求特点)。
  • 默认情况下把响应体当做无类型的 JSON 对象进行返回。如果指定了可选的模板类型 <Hero[]>,就会给返回你一个类型化的对象。其中,JSON 数据的具体形态是由服务器的数据 API 决定的。
  /*** Constructs a `GET` request that interprets the body as a JSON object and* returns the response body as a JSON object.** @param url     The endpoint URL.* @param options The HTTP options to send with the request.*** @return An `Observable` of the response body as a JSON object.*/get(url: string, options?: {headers?: HttpHeaders | {[header: string]: string | string[];};observe?: 'body';params?: HttpParams | {[param: string]: string | string[];};reportProgress?: boolean;responseType?: 'json';withCredentials?: boolean;}): Observable<Object>;
/* 查询操作 */
get(params): Observable<any> {return this.http.get(URL, {params:params}); // 这里的http为HttpClient实例
}

HttpClient.put()方法

方法参数:

  • URL 地址
  • body部分参数
  • options参数(可选)
  /*** Constructs a `PUT` request that interprets the body as a JSON object and returns the response* body as a JSON object.** @param url The endpoint URL.* @param body The resources to add/update.* @param options HTTP options** @return An `Observable` of the response, with the response body as a JSON object.*/put(url: string, body: any | null, options?: {headers?: HttpHeaders | {[header: string]: string | string[];};observe?: 'body';params?: HttpParams | {[param: string]: string | string[];};reportProgress?: boolean;responseType?: 'json';withCredentials?: boolean;}): Observable<Object>;
/* 修改操作 */
mod(params):Observable<any>{return this.http.put(URL, params);  // 这里的http为HttpClient实例
}

HttpClient.post()方法

方法参数:

  • URL地址
  • body部分参数
  • options参数(可选)
  /*** Constructs a `POST` request that interprets the body as a* JSON object and returns the response body as a JSON object.** @param url The endpoint URL.* @param body The content to replace with.* @param options HTTP options** @return An `Observable` of the response, with the response body as a JSON object.*/post(url: string, body: any | null, options?: {headers?: HttpHeaders | {[header: string]: string | string[];};observe?: 'body';params?: HttpParams | {[param: string]: string | string[];};reportProgress?: boolean;responseType?: 'json';withCredentials?: boolean;}): Observable<Object>;
/* 添加方法 */
add(params): Observable<any> {return this.http.post(URL, params); // 这里的http为HttpClient实例
}

HttpClient.delete()方法

  • URL地址
  • options参数(可选)
  /*** Constructs a `DELETE` request that interprets the body as a JSON object and* returns the response body as a JSON object.** @param url     The endpoint URL.* @param options The HTTP options to send with the request.** @return An `Observable` of the response, with the response body of type `Object`.*/delete(url: string, options?: {headers?: HttpHeaders | {[header: string]: string | string[];};observe?: 'body';params?: HttpParams | {[param: string]: string | string[];};reportProgress?: boolean;responseType?: 'json';withCredentials?: boolean;}): Observable<Object>;
/* 删除操作 */
del(no): Observable<any>  {return this.http.delete(URL + `/${no}`);  // 这里的http为HttpClient实例
}

添加和更新请求头

很多服务器都需要额外的头来执行保存操作。 例如,服务器可能需要一个授权令牌,或者需要 Content-Type 头来显式声明请求体的 MIME 类型。

添加请求头

import { HttpHeaders } from '@angular/common/http';const httpOptions = {headers: new HttpHeaders({'Content-Type':  'application/json',Authorization: 'my-auth-token'})
};

更新请求头

你不能直接修改前面的选项对象中的 HttpHeaders 请求头,因为 HttpHeaders 类的实例是不可变对象。请改用 set() 方法,以返回当前实例应用了新更改之后的副本。

下面的例子演示了当旧令牌过期时,可以在发起下一个请求之前更新授权头。

httpOptions.headers =httpOptions.headers.set('Authorization', 'my-new-auth-token');

—— END ——

Angular Http相关推荐

  1. Angular No name was provided for external module 'XXX' in output.globals 错误

    Angular 7 开发自定义库时,引用ngZorroAntd,build过程中出现 No name was provided for external module 'ng-zorro-antd' ...

  2. angular.isUndefined()

    <!DOCTYPE html> <html><head><meta charset="UTF-8"><title>ang ...

  3. 五:Angular 数据绑定 (Data Binding)

    通常来说,数据绑定要么是从页面流向组件中的数据,要么是从组件中的数据流向页面.下面我们来介绍在Angular 2中数据绑定的几种不同方式.  1. 使用{{}}将组件中的数据显示在html页面上  实 ...

  4. angular初步认识一

    最近比较流行MVC前端框架开发,最近研究了一个框架AngularJS框架 不说那么多,先上例子,我是个代码控 <!DOCTYPE html> <html lang="en& ...

  5. 【讲人话】Angular如何通过@ViewChildren获取实时渲染的动态DOM节点元素(@ViewChild只能获取静态的固定DOM节点)

    故事背景:有一天,强哥整了个动态渲染的列表代码如下 app.component.html <div><button (click)="add()">添加一行 ...

  6. Angular的ChangeDetectorRef.detectChanges()实现angularJS的$apply()方法,强制刷新数据渲染

    在Javascript代码里,都是按照一定顺序来执行的,当轮到一个代码片段执行的时候,浏览器就只会去执行当前的片段,不会做任何其他的事情.所以有时候一些做得不是很好的网页,当点击了某个东西之后会卡住, ...

  7. Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?

    有一天,我写了一个自信满满的自定义组件myComponent,在多个页面import使用了,结果控制台给我来这个 我特么裤子都脱了,你给我来这个提示是几个意思 仔细一看 The Component ' ...

  8. 【硬核解说】一口气讲明白Angular的5种路由守卫RouteGuard是嘛玩意儿

    Angular的常用路由守卫有5种,按照执行顺序: ① CanLoad:进入到当前路由的时候触发(若用户没有权限访问,相应的模块并不会被加载.这里是指对应组件的代码). ↓ ② CanAcitivat ...

  9. 浅谈Angular如何自定义创建指令@Directive

    ​知识普及 Angular 指令根据其创建形式分为内置指令和自定义指令,指令按照类型分: 模板指令--组件就是模板指令(只能自定义) 属性型指令 -- 更改元素.组件或其他指令的外观或行为的指令(有内 ...

  10. 【进阶玩法】Angular用emit()实现类似Vue.js的v-model双向绑定[(ngModel)]功能

    app.component.html <app-sizer [(ngModel)]="fontSizePx"></app-sizer> <p [sty ...

最新文章

  1. Spark Troubleshooting - Task not serializable问题分析
  2. stdthread(3)detach
  3. 云服务器系统重装为windows,并进行文件传输
  4. 【持续更新】JAVA面向对象多线程编程的一些tips
  5. PHP_SELF、 SCRIPT_NAME、 REQUEST_URI区别
  6. 计算机作文叙事,电脑争夺战叙事作文
  7. mysql 递归查询树型结构_MySQL递归查询所有子节点,树形结构查询
  8. 回头看看NSURLConnection
  9. Python最差实践
  10. 查看服务器是有有默认共享文件,服务器共享文件远程查看
  11. VS2012 安装出错 :通道正在关闭
  12. USB-C 端口在您的 Mac 上无法使用如何解决?
  13. 学做网站(1):环境搭建
  14. SpringCloud之Ribbon源码分析(二)
  15. windows下安装,配置gcc编译器
  16. 睡眠 应该用 a加权 c加权_困成狗?谈谈睡眠研究的遗传发现之旅
  17. The root link base_link has an inertia specified in the URDF, but KDL does not support a root ...
  18. HHKB 键盘 配置Mac 的 command 和 切换输入法
  19. BZOJ 1189 HNOI2007 紧急疏散evacuate
  20. Excel图形转入CorelDRAW技巧

热门文章

  1. leetcode-2 两数相加
  2. 安卓相对布局常用语句
  3. 一个在raw里面放着数据库文件的网上例子
  4. STM32GPIO管脚设置
  5. mybatis-错误记录java.lang.ExceptionInInitializerError
  6. apue学习之文件IO第二部分
  7. Linux系统轻量级监控工具monitorix和munin安装
  8. Linux环境编译安装Mysql以及PHP中文乱码解决
  9. C#表达式,类型和变量
  10. 有规律格式化文本文件插入数据库