Angular Http

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 HTTPAngular框架的一个模块,用于处理HTTP请求和响应。它提供了一组功能强大的API,可以方便地进行HTTP通信。在Angular,可以使用HttpClient模块来发送HTTP请求,并使用Observables来处理响应。 要在Angular使用HTTP模块,首先需要在应用的根模块或特定模块导入HttpClientModule。例如,在app.module.ts文件,可以使用以下代码导入HttpClientModule: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, HttpClientModule, // ... 其他模块 ... ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule {} 一旦导入了HttpClientModule,就可以在组件注入HttpClient服务,并使用它来发送HTTP请求。例如,可以在组件注入HttpClient,并使用get()方法发送一个简单的GET请求: import { HttpClient } from '@angular/common/http'; @Component({ // 省略组件的其他配置 }) export class MyComponent { constructor(private http: HttpClient) {} getData() { this.http.get('http://example.com/api/data').subscribe((response) => { // 处理响应数据 }); } } 以上示例代码演示了如何使用Angular HTTP模块发送一个简单的GET请求。根据实际需求,还可以使用HttpClient模块发送POST、PUT、DELETE等类型的请求,并使用不同的参数和选项来定制请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值