Angular22 HttpClient的使用

 

1 HttpClient介绍

  HttpClient时Http的演进,注意:Http在@angular/http中,而HttpClient在@angular/common/http中; 使用前需要在模块级别导入HttpClientModule,通常的做法是在核心模块中导入,在将核心模块导入到主模块中

 

2 HttpClient特性说明

  2.1 默认JSON解析

    HttpClient使用的默认数据格式就是JSON,所以不需要在利用map进行数据格式转化了,即:http.get(url).map(res => res.json()).subscribe(...)将被http.get(url).subscribe(...)代替;

  2.2 拦截器

    待更新......

    2018-3-12 15:00:20

    参考博文:点击前往

 

3 HttpClient编程步骤

  3.1 导入HttpClientModule

    在模块级别导入HttpClientModule

    技巧01:直接在主模块中导入即可,但是一般的做法是将一些只导入一次的模块放到一个核心模块中,再将核心模块导入到主模块中即可

import { NgModule,  SkipSelf, Optional } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HeaderComponent } from './header/header.component';
import { MainComponent } from './main/main.component';
import { FooterComponent } from './footer/footer.component';

import 'hammerjs';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { SidenavComponent } from './sidenav/sidenav.component';
import { SharedModule } from '../shared/shared.module';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserAnimationsModule,
    SharedModule,
    RouterModule,
    HttpModule,
    HttpClientModule
  ],
  declarations: [
    HeaderComponent,
    MainComponent,
    FooterComponent,
    SidenavComponent
  ],
  exports: [
    HeaderComponent,
    MainComponent,
    FooterComponent,
    SidenavComponent
  ]
})
export class CoreModule { 
  constructor( @Optional() @SkipSelf() parent: CoreModule) {
    if (parent) {
      throw new Error('核心模块已经加载了,请勿重复加载');
    }
  }
}
核心模块

    坑01:和表单相关的模块不能在核心模块中导入,只能在共享模块中导入,再将需要用到表单的模块中导入共享模块

  3.2 创建一个Http服务

    创建一个服务文件专门来存放一些执行Http请求的方法,在该服务中依赖注入 HttpClient,利用HttpClient对象去执行Http请求

    坑01:HttpClient对象提供的get、post、delete、put方法的返回值都是一个已经转化成了JSON数据的JavaScript对象,如果想获取该对象中的某个属性就必须使用  对象名[ ‘属性名’ ]  这样的格式,不能使用   对象名.属性名  这种格式;如果使用   对象名.属性名   这种格式时就必须在调用HttpClient对象提供的方法时通过泛型来对响应数据进行类型指定,例如:

      

    

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ClientBaseInfo, responseResult } from '../model/ClientBaseInfo';

@Injectable()
export class TestService {

    constructor(
        private http: HttpClient
    ) {}

    testGet() {
        return this.http.get<responseResult<ClientBaseInfo>>('http://127.0.0.1:8888/dev/client/findAll');
    }

}
Http服务

  3.3 依赖注入Http服务

     在模块级别依赖注入自己定义的Http服务

    

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Test01Component } from './test01/test01.component';
import { CoreModule } from '../core/core.module';
import { TestHomeComponent } from './test-home/test-home.component';
import { SharedModule } from '../shared/shared.module';
import { TestRoutingModule } from './test-routing.module';
import { Test02Component } from './test02/test02.component';
import { Test03Component } from './test03/test03.component';
import { TestDemoComponent } from './test-demo/test-demo.component';
import { HttpModule } from '@angular/http';
import { TestService } from './test.service';

@NgModule({
  imports: [
    SharedModule,
    TestRoutingModule
  ],
  declarations: [
    TestHomeComponent,
    Test01Component,
    Test02Component,
    Test03Component,
    TestDemoComponent
  ],
  exports: [
    Test01Component
  ],
  providers: [
    TestService
  ]
})
export class TestModule { }
模块级别依赖注入Http服务

  3.4 执行Http请求

    在组件中调用Http服务提供的方法发送Http请求

    

     坑01:当响应数据的结果是多个同类型的对象组成的实例组成的列表时,如果想将这个列表赋值给一个指定了类型的的列表是会报类型错误的,例如:响应数据是 [ a, b, c, d ]  其中 a b c d 都是 Person类 的实例,现在将 [ a , b, c, d ] 赋值给 result 其中 result 的类型是 Person[] , 这时候就会包类型错误 -> 不能将类型“Person”分配给类型“Person[]”,但是如果将result类型改成Person就会编译成功,而且还可以在视图中把result当成一个列表来使用;具体原因不详。

 

4 HttpClient实现CRUD实例

  在实际的生产环境中是不会删除数据的,只会修改数据的有效状态,所以不会用到DELETE

import { Injectable } from '@angular/core';
import { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';
// import { Http } from '@angular/http'
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { ClientBaseInfo, ResponseResult } from '../model/ClientBaseInfo';

@Injectable()
export class ClientService {
    constructor(
        // private http: Http
        private http: HttpClient
    ) {}

    // 查询所有的客户信息
    getClientInfo() {
        // 利用Http实现
        // return this.http.get('http://localhost:3333/clientBaseInfo').map(result => result.json());

        // 利用HttpClient实现
        // return this.http.get('http://localhost:3333/clientBaseInfo');
        return this.http.get<ResponseResult<ClientBaseInfo>>('http://127.0.0.1:8888/dev/client/findAll');
    }

    // 根据姓名查询客户信息
    getClientInfoByName(name: string) {
        const params = new HttpParams()
            .set('name', name);
        const headers = new HttpHeaders().set("Content-Type", "application/json");

        return this.http
                    .get<ResponseResult<ClientBaseInfo>>(
                        'http://127.0.0.1:8888/dev/client/findByName', 
                        {params, headers}
                    )
    }

    getClientInfoByIdcard(idcard: string) {
        const params = new HttpParams()
                            .set('idcard', idcard);
        const headers = new HttpHeaders().set("Content-Type", "application/json");
        return this.http.get<ResponseResult<ClientBaseInfo>>(
                            'http://127.0.0.1:8888/dev/client/findByIdcard',
                            {params, headers}
                        );
    }

    // 新增客户信息
    createClientInfo(clientBaseInfo: ClientBaseInfo) {
        const headers = new HttpHeaders().set("Content-Type", "application/json");
        // const body = {
        //   "name": "郭靖",
        //   "phone": "12272222616",
        //   "address": "襄阳城",
        //   "gender": "男",
        //   "idcard": "500228199210031925",
        //   "hometown": "西北边塞",
        //   "remarks": "降龙十八掌",
        //   "status": 1
        // };
        const body = clientBaseInfo;
        return this.http.post<ResponseResult<Object>>('http://127.0.0.1:8888/dev/client/create', body, {headers});
    }

    // 修改客户信息
    updateClientInfo(clientBaseInfo: ClientBaseInfo) {
        const headers = new HttpHeaders().set("Content-Type", "application/json");
        // const body = {
        //   "name": "郭靖",
        //   "phone": "12272222616",
        //   "address": "襄阳城",
        //   "gender": "男",
        //   "idcard": "500228199210031933",
        //   "hometown": "西北边塞",
        //   "remarks": "爱吃烤全羊",
        //   "status": 1
        // };
        const body = clientBaseInfo;
        return this.http.put<ResponseResult<Object>>('http://127.0.0.1:8888/dev/client/update', body, {headers});
    }

    test(clientBaseInfo: ClientBaseInfo) {
        const headers = new HttpHeaders().set("Content-Type", "application/json");
        const body = clientBaseInfo;
        return this.http.put('http://127.0.0.1:8888/dev/client/update', body, {headers});
    }

}
View Code

 

 

 

 

 

           

posted @ 2018-03-12 15:26  寻渝记  阅读(524)  评论(0编辑  收藏  举报