发表于: 2020-07-01 21:36:18

1 2322


今天完成的事情:今天看了不同的请求的方法区别
明天计划的事情:继续后效的任务
遇到的问题: angular的请求还是不太熟练写法也不够简练
收获:通过angular自身的代理转发功能

创建json文件


配置package.json 

启动项目通过npm start启动,会自动启动代理服务npm start


Angular-cli新建httpClientExample项目
ng new httpClientExample
ngModule中导入HttpClientModule
typescript
....
import { HttpClientModule } from '@angular/common/http';
....
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

npm安装json-server,代替api server提供API服务。(windows命令行提示符(管理员))

npm install -g json-server

新建一各 JSON 文件,扮演我们的服务器上的数据库。

{
    "customers": [
        {
            "id": 1,
            "name": "Customer001",
            "email": "customer001@email.com",
            "tel": "0526252525"
        },
        {
            "id": 2,
            "name": "Customer002",
            "email": "customer002@email.com",
            "tel": "0527252525"
        },
        {
            "id": 3,
            "name": "Customer003",
            "email": "customer003@email.com",
            "tel": "0528252525"
        }

    ]
}

启动服务。现在可像用Rest service进行查询

json-server --watch E:\db.json

HttpClient Get请求。

  1. 导入HttpClient , @angular/common/http
  2. component 构造函数中注入HttpClient
  3. 使用.get(端点)方法创建HTTP GET请求
  4. 订阅(Subscribe )返回的observable并显示结果

import { Component,OnInit } from '@angular/core';//OnInit 接口,要求实现OnInit方法。
import { Observable } from "rxjs/Observable";//add
import { HttpClient, } from "@angular/common/http";/add
class Customer {
id : number;
namestring;
emailstring;
telstring;
}    
@Component({
selector: 'customers',
template: `
  <ul *ngIf="customersObservable | async as customers else empty">
      <li *ngFor="let customer of customers">
      {{customer|json}}
      </li> 
  </ul>
`})   
export class AppComponent implements OnInit {
customersObservable : Observable<Customer[]>;    
title = 'app';      
constructor(private httpClient:HttpClient) {
}
ngOnInit() {//初始化时就开始get请求数据
this.customersObservable = this.httpClient
    .get<Customer[]>("127.0.0.1:3000/customers");
}
}

HTTP GET 请求参数: HttpParams

请求第1页,最大条数2:

  1. url方式
    http://127.0.0.1:3000/customers?_page=1&_limit=1

使用httpClient实现

  1. 导入HttpParams
    import {HttpParams} from "@angular/common/http";

     2. 构建一个 HttpParams 对象
const params = new HttpParams().set('_page', "1").set('_limit', "1");

呼叫 .get() 方法并携带参数,然后将返回的 Observable 对象分配给customersObservable。(params 要与get在同一个方法中)

this.customersObservable = this.httpClient.get("http://127.0.0.1:3000/customers", {params});

使用更简单的方法新建HttpParams对象:【fromString】

const params = new HttpParams({fromString: '_page=1&_limit=1'});

添加 HTTP Headers

导入HttpHeaders
import { HttpHeaders } from '@angular/common/http';

新建客制的HttpHeader对象
const headers = new HttpHeaders().set("X-CustomHttpHeader", "CUSTOM_VALUE");

送带httpHeader的请求

const headers = new HttpHeaders().set("X-CustomHttpHeader", "CUSTOM_VALUE");

this.customersObservable = this.httpClient.get("http://127.0.0.1:3000/customers", {headers});

携带httpHeader,会出现重复请求的状况,第一次Option请求 204状态(Firefox 为Option请求方法),第二次为返回的结果。

发送HTTP PUT 请求
HTTP PUT 方法用来完全替换 API server上的资源。用HttpClient 发送PUT 请求替换Customers上id为1的资源:

this.httpClient.put("http://127.0.0.1:3000/customers/1",
    {
        "name": "NewCustomer001",
        "email": "newcustomer001@email.com",
        "tel": "0000252525"
    })
    .subscribe(
        data => {
            console.log("PUT Request is successful "data);
        },
        error => {
            console.log("Rrror"error);
        }
    );

还有很多其他的方法运用,明天在继续


返回列表 返回列表
评论

    分享到