史上最方便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-httphtml

angular5簡單暴力封裝table,實戰乾貨

相關文章
相關標籤/搜索