史上最方便http请求封装-angular

  • 使用方法如下,超级方便吧!
<div class="container">
  <div class="card" *get="let item of src;code as code;msg as msg;url as url;">
    <div class="card-header">
      GET请求接口:{{src}}
    </div>
    <div class="card-body">
      状态码:{{code}}
      <br> 备注说明: {{msg}}
      <br> 返回数据: {{item | json}}
      <br> 请求链接: {{url}}
    </div>
  </div>

  <div class="card" *post="let item of src;params params;body {id: 2}; code as code; msg as msg;url as url;">
    <div class="card-header">
      POST请求接口:{{src}}
    </div>
    <div class="card-body">
      状态码:{{code}}
      <br> 备注说明: {{msg}}
      <br> 返回数据: {{item | json}}
      <br> 请求链接: {{url}}
      <br> 请求数据: {{params|json}}
    </div>
  </div>
</div>
复制代码
  • get封装
import { Directive, Input, ViewContainerRef, TemplateRef } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { UrlService } from "./url.service";
/*
  *get="let item of url"
*/
@Directive({
  selector: "[get][getOf]"
})
export class GetDirective {
  @Input() getOf: string;
  @Input() getParams: string;

  constructor(
    public http: HttpClient,
    public view: ViewContainerRef,
    public template: TemplateRef<any>,
    public url: UrlService
  ) {}

  ngOnInit() {
    let url = this.url.getOpenUrl(this.getOf, this.getParams);
    this.http.get(url).subscribe((res: any) => {
      this.view.createEmbeddedView(this.template, {
        $implicit: res.data,
        code: res.code,
        msg: res.msg,
        url: url
      });
    });
  }
}

复制代码
  • post封装
import { Directive, Input, ViewContainerRef, TemplateRef } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { UrlService } from "./url.service";
/*
  *post="let item of url;params params;"
*/
@Directive({
  selector: "[post][postOf]"
})
export class PostDirective {
  @Input() postOf: string;
  @Input() postParams: any;
  @Input() postBody: any;
  constructor(
    public http: HttpClient,
    public view: ViewContainerRef,
    public template: TemplateRef<any>,
    public url: UrlService
  ) {}

  ngOnInit() {
    let url = this.url.getOpenUrl(this.postOf, this.postParams);
    this.http.post(url, this.postBody).subscribe((res: any) => {
      this.view.createEmbeddedView(this.template, {
        $implicit: res.data,
        code: res.code,
        msg: res.msg,
        url: url
      });
    });
  }
}

复制代码

安装

yarn add iwe7-http
复制代码

总结

感叹我大NG的强大!iwe7-http

angular5简单暴力封装table,实战干货

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值