angular入门篇8----Http模块的使用(2):使用接口

angular入门篇8----Http模块的使用(2):使用接口

1.创建Http服务

1.1 注册HttpClientModule模块

我们需要在model.module.ts中注册HttpClientModule模块:
\Store\src\app\model\module.model.ts
img

1.2 创建http服务

随后,创建一些http服务:

\Store\src\app\model下创建:rest.datasourse.ts

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs"; import { Product } from "./product.model"; import { Order } from "./order.module"; const PROTOCOL = "http"; const PORT = 3500; @Injectable() export class RestDataSource { baseUrl : string; auth_token : string|null =null; constructor(public http: HttpClient){ this.baseUrl = `${PROTOCOL}://${location.hostname}:${PORT}/`; } getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.baseUrl+"products"); } saveOrder(order: Order): Observable<Order> { return this.http.post<Order>(this.baseUrl+"order",order); } }

tip:记得在module.model.ts中注册RestDataSource模块,这里就不重复了。

Angular中http的使用是与rxjs的Observable绑定的,作者尚未对所谓"订阅者模式"有很深刻的理解,所以这里只是奉上代码。

需要提一下的是,《Angular5》中作者是使用request方法代替上述的post、get方法的。但request方法写得很宽泛,返回类型是"Product[] | Order[]",但目前的typescript似乎不支持这种写法,因此博主将代码改写成了上面的写法。

1.3 代替原先的静态数据

\Store\src\app\model\order.repository.ts
img
\Store\src\app\model\product.repository.ts
img

最后我们在Checkout.component.ts中打印一下订单:

\Store\src\app\store\checkout.component.ts
img

2. 效果展示

2.1 运行项目

这里我们需要运行接口服务和项目,因此需要建立两个终端,具体操作如下:
img

2.2 项目效果

此时我们运行项目,就可以看到被替换的数据:
img
img
img

posted @   Feo2022  阅读(136)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开