Angular4 数据请求 POST、GET

创建项目

ng new OBJECT_NAME

创建一个名为 httpRequest  的服务

ng generate service httpRequest 

在app.module.ts 里面添加

providers : [HttpRequestService]

HttpRequestService.ts 文件

import { Injectable, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class HttpRequestService {

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json;application/x-www-form-urlencodeed; charset=utf-8'})
  };

  constructor(private httpClient : HttpClient) { }

  httpPost(reqUrl : string, reqBody, comp, flag) {
    //后台接收数据 需要 @RequestBody 标签
    this.httpClient.post(reqUrl, reqBody, this.httpOptions)
    .subscribe(
      val => {
        console.log('post请求成功', val);
        
        if(val['success']){
          comp.postOk(val, flag);
        }else{
          comp.postErr(val, flag);
        }
      },
      error => {
        console.log('post请求失败', error);
        comp.postErr(error, flag);
      }
    );
    
  }

  httpGet(reqUrl, comp, flag){
    this.httpClient.get(reqUrl, this.httpOptions)
    .subscribe(
      val => {
        console.log('get请求成功', val);
        
        if(val['success']){
          comp.getOk(val, flag);
        }else{
          comp.getErr(val, flag);
        }
        
      },
      error => {
        console.log('get请求失败', error);
        comp.getErr(error, flag);
      }
    );
  }

  show() : string {
    return '我是 HttpRequestService 调用我干嘛';
  }



}
创建一个名为 sku-from 的组件

ng g component sku-from

sku-form.component.html 文件

<div>
  sku-form works!
  <form #skuForm="ngForm" (ngSubmit)="onSubmit(skuForm)">
    <div class="form-group">
      <label for="name">货品代码</label>
      <input type="text" class="form-control" [(ngModel)]="skuInfo.sku" name="sku" required minlength="4" />
    </div>

    <div class="form-group">
      <label for="alterEgo">货品描述</label>
      <input type="text" class="form-control" [(ngModel)]="skuInfo.descr" name="descr" required />
    </div>
    <br/>
    <button type="button" nz-button [nzType]="'dashed'" (click)="newSku()">new sku</button>
    <button type="submit" nz-button [nzType]="'primary'">Submit</button>
  </form>
</div>
sku-form.component.ts文件
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators }   from '@angular/forms';

import {HttpRequestService} from '../httpRequest.service'

import {Sku} from './../sku';

@Component({
  selector: 'app-sku-form',
  templateUrl: './sku-form.component.html',
  styleUrls: ['./sku-form.component.css']
})
export class SkuFormComponent implements OnInit {

  private api_sku_save = 'http://localhost:8081/sino-web/bas/sku/saveDetails';
  private skuInfo : Sku = new Sku(1, '0000000000010', '红牛', new Date());
  private skuForm : FormGroup;
  
  reqsuccess : boolean;
  reqsuccessMsg : string;

  constructor(private httpRequestService : HttpRequestService) {
    this.createForm();
   }
  ngOnInit() { }

  createForm(){
    this.skuForm = new FormGroup({
      sku : new FormControl(this.skuInfo.sku, Validators.minLength(7)),
      descr : new FormControl(this.skuInfo.descr, Validators.required)
    });
  }
  newSku(){
    this.skuInfo = new Sku(null, '', '', null);
  }
  onSubmit(formData) {
/** 
         * valid:是否有效、 invalid:无效、dirty:脏\status:状态、errors:显示错误
         */
    if(formData.form.valid){
      this.httpRequestService.httpPost(this.api_sku_save, this.skuInfo, this, 'save');
    }

  }

  postOk (val, flag){
    this.reqsuccess = true;
    this.reqsuccessMsg = '';
  }
  postErr (val, flag){
    this.reqsuccess = false;
    this.reqsuccessMsg = val['msg'];
    console.log(val);
  }

  
}

创建一个名为 sku的类

ng g generate class Sku

sku.ts文件

export class Sku {

    constructor(
        public id : number,
        public sku : string,
        public descr : string,
        public createdAt : Date
    ){}
}

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值