为了账号安全,请及时绑定邮箱和手机立即绑定

HTTP 服务

基本概念

HTTP 服务指的是通过 HTTP 协议与远程服务器进行通讯的一种方式。
Angular 有自己独立的 HTTP 模块。

使用 HTTP 服务

项目截图:

图片描述

1、在模块装饰器 @NgModule 中导入 HttpClientModule:

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

// 导入 HttpClientModule
// 由于整个应用都会使用到 HTTP 服务,所以通常在根模块中导入 HttpClientModule
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,

    // 将 HttpClientModule 加入到 imports 数组中
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2、在服务文件中导入 HttpClient,并在构造函数中声明:

api.service.ts

import { Injectable } from '@angular/core';

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

@Injectable()
export class ApiService {

constructor(

  // 声明 HttpClient
  private http: HttpClient
  ) { }
  
  // 定义与服务器交互的 doGet() 方法
  doGet(name: string) :Promise<any> {
    return this.http
        .get(`http://localhost:8081/person?name=${name}`)
        .toPromise()
        .then((response: any) => {
          return response;
        })
        .catch((err) => console.log(err));
  }

}

3、在 AppComponent 组件中调用 doGet() 方法:

app.component.ts

import { Component, OnInit } from '@angular/core';

// 导入服务 ApiService
import { ApiService } from 'src/app/common/service/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],

  // 注入服务 ApiService
  providers: [
    ApiService
  ],
})
export class AppComponent implements OnInit {

  constructor(

    // 初始化服务 ApiService
    private apiService: ApiService
  ){}

  ngOnInit(){

    // 调用 doGet() 方法
    this.apiService.doGet('Tom').then((data :any)=>{
      console.log(data); // 输出:{msg: '查询成功'}
    });
  }
}

服务器端的方法:

// node.js

var express = require('express');
var app = express();

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("X-Powered-By",' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
 
app.get('/person', function (req, res) {
   res.send(JSON.stringify({"msg":"查询成功"}));
});

app.post('/creat', function (req, res) {
  res.send(JSON.stringify({"msg":"新增成功"}));
});

app.put('/updata', function (req, res) {
  res.send(JSON.stringify({"msg":"修改成功"}));
});

app.delete('/delete', function (req, res) {
  res.send(JSON.stringify({"msg":"删除成功"}));
});
 
var server = app.listen(8081, function () {});

请求类型

上面例子中,我们了解了 GET 请求的使用方法,而其他类型的请求也很重要。

  • POST 和 PUT 请求带有一个 URL 和一个请求体。
  • GET 和 DELETE 请求只带有一个 URL,没有请求体。

例子:

api.service.ts

  // GET 请求
  // 通常用于获取数据
  doGet(name: string) :Promise<any> {
    return this.http
        .get(`http://localhost:8081/person?name=${name}`)
        .toPromise()
        .then((response: any) => {
          return response;
        })
        .catch((err) => console.log(err));
  }

  // DELETE 请求
  // 通常用于删除数据
  doDelete(id: string) :Promise<any>  {
    return this.http
      .delete(`http://localhost:8081/delete?id=${id}`)
      .toPromise()
      .then((response: any) => {
        return response;
      })
      .catch((err) => console.log(err));
}

  // POST 请求
  // 通常用于添加数据
  doPost(param: any) :Promise<any>  {
      return this.http
        .post('http://localhost:8081/creat', param)
        .toPromise()
        .then((response: any) => {
          return response;
        })
        .catch((err) => console.log(err));
  }

  // PUT 请求
  // 通常用于更新或添加数据
  doPut(param: any) :Promise<any>  {
      return this.http
        .put('http://localhost:8081/updata', param)
        .toPromise()
        .then((response: any) => {
          return response;
        })
        .catch((err) => console.log(err));
  }

app.component.ts

// 调用 doGet() 方法
this.apiService.doGet('Tom').then((data :any)=>{
  console.log(data); // {msg: '查询成功'}
});

// 调用 doDelete() 方法
this.apiService.doDelete('123').then((data :any)=>{
  console.log(data); // {msg: '删除成功'}
});

// 调用 doPost() 方法
this.apiService.doPost({name:'Tom'}).then((data :any)=>{
  console.log(data); // {msg: '新增成功'}
});

// 调用 doPut() 方法
this.apiService.doPut({name:'Tom'}).then((data :any)=>{
  console.log(data); // {msg: '修改成功'}
});

HttpHeaders

新建或修改 HTTP 请求标头,通常用于向服务器发送授权令牌。

例子:

api.service.ts

import { Injectable } from '@angular/core';

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

@Injectable()
export class ApiService {

  // 实例化 HttpHeaders
  headers = new HttpHeaders();

constructor(
  private http: HttpClient
  ) { }
  
  doGet(name: string) :Promise<any> {

    // 添加键值对
    let headers = this.headers.set('USER_ID','admin');
    return this.http
         // 作为 GET 和 DELETE 请求的第二个参数
        .get(`http://localhost:8081/person?name=${name}`,{ headers :headers })
        .toPromise()
        .then((response: any) => {
          return response;
        })
        .catch((err) => console.log(err));
  }

  doPost(param: any) :Promise<any>  {

    // 添加键值对
    let headers = this.headers.set('TOKEN','user');
    return this.http
      // 作为 POST 和 PUT 请求的第三个参数
      .post('http://localhost:8081/creat', param, { headers :headers })
      .toPromise()
      .then((response: any) => {
        return response;
      })
      .catch((err) => console.log(err));
  }

}

图片描述

图片描述

HttpParams

序列化请求参数,通常用于GET 和 DELETE 请求。

例子:

api.service.ts

import { Injectable } from '@angular/core';

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

@Injectable()
export class ApiService {

  headers = new HttpHeaders();

  // 实例化 HttpParams
  search = new HttpParams();

constructor(
  private http: HttpClient
  ) { }
  
  doGet(name: string) :Promise<any> {

    // 序列化 URL 上的参数
    let search = this.search.set('name', name);
    return this.http
        // 省略了在 URL 后面拼接字符串
        .get(`http://localhost:8081/person`,{ params: search, headers :this.headers })
        .toPromise()
        .then((response: any) => {
          return response;
        })
        .catch((err) => console.log(err));
  }

  doDelete(id: string) :Promise<any>  {

    // 序列化 URL 上的参数
    let search = this.search.set('id', id);
    return this.http
      // 省略了在 URL 后面拼接字符串
      .delete(`http://localhost:8081/delete`,{ params: search, headers :this.headers })
      .toPromise()
      .then((response: any) => {
        return response;
      })
      .catch((err) => console.log(err));
}

}

图片描述


end

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
1.4万
获赞与收藏
860

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消