一、引用
引用即使用前的准备,要使用http请求,根据mvc的模块设计,应该从model层入手,即在service中使用。
1.1 在app.module.ts中导入HttpClientModule模块
import { HttpClientModule } from '@angular/common/http';
二、使用
2.1 在service层中引入并使用
cart.services.ts:
/*
* @Author: tom
* @Date: 2019-11-10 13:03:06
* @Last Modified by: tom
* @Last Modified time: 2019-11-10 15:11:12
*/
import { Injectable } from '@angular/core';
import { products } from 'src/assets/products';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CartService {
// 构建数组,保存加入购物车的product对象
items = [];
constructor(
private http: HttpClient
) { }
// 添加到购物车
addToCart(product) {
this.items.push(product);
}
// 清空购物车
clearCart() {
this.items = [];
return this.items;
}
// 获取购物车内容,用于购物车组件界面显示
getItem() {
return this.items;
}
// 通过http请求获取到需要的数据,并返回给控制层
getShippingByHTTP() {
return this.http.get('../../assets/shipping.json');
}
}
此处即为通过http的get请求方式获取到json数据
]
shipping.json:
[
{
"type": "Overnight",
"price": 25.99
},
{
"type": "2-Day",
"price": 9.99
},
{
"type": "Postal",
"price": 2.99
}
]
2.2 在购物车中使用
product-shipping.component.ts:
import { CartService } from './../../Service/cart.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-shipping',
templateUrl: './product-shipping.component.html',
styleUrls: ['./product-shipping.component.css']
})
export class ProductShippingComponent implements OnInit {
shippingCosts;
constructor(
private cartService : CartService
) {
this.shippingCosts = this.cartService.getShippingByHTTP();
}
ngOnInit() {
}
}
product-shipping.component.html:
<!-- /*
* @Author: tom
* @Date: 2019-11-10 14:58:48
* @Last Modified by: tom
* @Last Modified time: 2019-11-10 14:58:48
* @Description: this view is used to see the price of shipping.
the price data are comming from http request,
so we should add async for get async data.
*/ -->
<p>
product-shipping works!
</p>
<h3>Shipping Price</h3>
<!-- get async data from http request. and respose data is a array. -->
<div *ngFor="let item of shippingCosts | async">
{{item.type}}
{{item.price | currency}}
</div>
可以看到在for循环获取数据时,我还加了一层 async管道,async会将这一个模块包装进一个异步测试区域。当该区域中的所有异步调用都已完成时,这个dom结构会自动渲染。
得到最终结果: