(终极篇章 二)实战中服务器通讯细节(http&webSocke)

马上就写完了,后期还要有大量更改,有看不懂的地方,直接评论。—— 马丁路德.东

给get请求添加请求数据

因为我们得到原始搜索条件和渲染数据的组件不是一个,我们选用一个公共服务作为中间人。

(一)我们在公共服务中添加方法,(完成得到数据和发起请求的功能)

1.定义搜索条件的格式

export class  ProductSearchParams{
  constructor(
    public title: string,
    public price: number,
    public category: string
  ){}
}

2.发起HTTP请求

 search(params: ProductSearchParams): Observable<Product[]>{
    return this.http.get('/api/products', {search:this.encodeParams(params)}).map(res => res.json());
  }

3.整理搜索条件(es6新语法)

private encodeParams(params: ProductSearchParams) {
    return Object.keys(params)
      .filter(key => params[key])
      .reduce((sum: URLSearchParams, key:string) => {
        sum.append(key, params[key]);
        return sum;
      }, new URLSearchParams());
  }

4.在服务中定义一个事件流,以供双方使用

searchEvent:EventEmitter<ProductSearchParams> = new EventEmitter();

(二)在需要渲染数据的地方,订阅此流(使用查询参数调取搜索方法,得到数据)

export class ProductComponent implements OnInit {
  private products: Observable<Product[]>;
   constructor( private  productService: ProductService) { }

  ngOnInit() {
 this.products=this.productService.getProducts();
    this.productService.searchEvent.subscribe(  params => this.products = this.productService.search(params)
    );
  }

}

(三)表单组建发送事件(表单得到的数据类型,和http所需要的查询参数格式,是完全一致的)

onSearch(){
    if(this.formModel.valid){
      console.log(this.formModel.value);
      this.productServecie.searchEvent.emit(this.formModel.value);
    }
  }

(四)服务器端代码思想实现搜索(“-1”代表所有类型)

app.get('/api/products',(req,res)=>{
    let result = products;
    console.log("服务器已经接受到了商品列表请求");
    let params = req.query;
    if(params.title){
        result = result.filter((p) => p.title.indexOf(params.title) !== -1)
    }
    if(params.price && result.length){
        result = result.filter((p) => p.price <=parseInt(params.price));
    }
    console.log(params.category);

    if(params.category !== "-1" && result.length){
        result = result.filter((p) => p.categories.indexOf(params.category) !== -1)
    }
    res.json(result);
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,064评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,080评论 25 709
  • 1. 网络基础TCP/IP HTTP基于TCP/IP协议族,HTTP属于它内部的一个子集。 把互联网相关联的协议集...
    yozosann阅读 8,781评论 0 20
  • 你总是和我说谢谢,说谢谢我在这段时间里陪着你。殊不知,最该说谢谢的人是我,谢谢你给了我继续活着的理由。 长时间的失...
    九月Monica阅读 1,567评论 0 1
  • 人类的肉体交易,可谓是源远流长。这个话题太古老了,堪称是一项跨越时代的身体资源开发。它的存在,不分古今,不分内外,...
    命自我立阅读 1,837评论 4 2

友情链接更多精彩内容