实战Angular2+web api增删改查(三)

前端之家收集整理的这篇文章主要介绍了实战Angular2+web api增删改查(三)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Angular2 开发

本示例使用了Angular2 RC4版本,另外由于使用了bootstrap,所以需要html中引入对应的css及js文件

入口

import { bootstrap } from '@angular/platform-browser-dynamic';
import {myApp} from "./myApp";
import {HTTP_PROVIDERS} from "@angular/http";
bootstrap(myApp,[HTTP_PROVIDERS]).catch(err=>console.error(err));

这里由于要使用angular中的http所以需要在入口处先注入

服务

在此之前我们需要先定义DTO,由于我们传输DTO使用的是Json格式所以angular的DTO与webapi中DTO类型名称一致即可。

export interface groupDto {
 ID:string;
 GROUPNAME:string;
 NORDER:number;
 PARENTID:string;
 GROUPTYPE:string;
 GROUPCODE:string;
}

下面将定义groupservice来从webapi中获取数据、更新数据

/** * Created by Administrator on 2016-06-30. */ import {Injectable} from "@angular/core";
import {Http,Headers} from "@angular/http";
import 'rxjs/Rx';
import {groupDto} from "./models/groupDto";
import {Observer,Observable} from "rxjs/Rx";
@Injectable()
export class groupservice{
 isSubmit:Observable<boolean>;
 private observer:Observer<boolean>;

 private _baseURL: string="http://localhost:23273/api/GroupList";
 constructor(private _http: Http) {
 this.isSubmit= new Observable<boolean>(observer=>this.observer=observer).share();
 }
 getGroupList() {

 return this._http.get(this._baseURL).map(responce => responce.json());
 }
 getGroup(id:string){
 return this._http.get(this._baseURL+"/"+id).map(responce => responce.json());
 }
 addGroup(item:groupDto){
 var json = JSON.stringify(item);
 var params = 'json=' + json;
 var headers = new Headers();
 headers.append('Content-Type','application/json');
 headers.append('Accept','application/json');

 return this._http.post(this._baseURL,JSON.stringify(item),{headers: headers}).subscribe(
 data=>{console.log(data);},err => {console.log(err);},() => {
 console.log("Complete");
 if(this.observer!==undefined)
 this.observer.next(true);

 }
 );
 }
 editGroup(id:string,item:groupDto){
 var json = JSON.stringify(item);
 var params = 'json=' + json;
 var headers = new Headers();
 headers.append('Content-Type','application/json');

 return this._http.put(this._baseURL+"/"+id,() => {
 console.log("Complete");
 if(this.observer!==undefined)
 this.observer.next(true);

 }
 );
 }
 delGroup(id:string){
 var headers = new Headers();
 headers.append('Content-Type','application/json');
 return this._http.delete(this._baseURL+"/"+id).subscribe(
 data=>{console.log(data)},err=>{console.log(err)},()=> {
 console.log("Complete");
 if (this.observer !== undefined)
 this.observer.next(true);
 }
 );
 }
}

这里可以看到这个服务申明了@Injectable()也就是说是可被注入的,在这个服务的构造中我们注入http服务,为了保证我们数据更新能够被其他组件检测到故在此还是用了观察模式(isSubmit),在数据更新后需要发布这个(isSubmit)变化,即可保证凡是订阅了该变化的组件都可及时进行数据处理。

这里重点需要注意在调用http传递参数时需要加入http的头部信息,指定参数格式为Json。

父组件定义

/** * Created by Administrator on 2016-06-30. */ import {Component,ViewChild} from "@angular/core";
import {groupservice} from "./group.Service";
import {groupDto} from "./models/groupDto";
import {addgroup} from "./addgroup.component";
import {ConfirmOptions} from "../components/confirm/confirmOptions.provider";
import {Confirm} from "../components/confirm/confirm.directive";
import {ConfirmPopover} from "../components/confirm/confirmPopover.component";
import {Position} from "../components/confirm/position.provider" import {PositionService} from "../components/confirm/position/position";
import {editgroup} from "./editgroup.component";
@Component(
 {
 selector:"group",templateUrl:"./app/curd/groupmanager.html",providers:[groupservice,ConfirmOptions,{provide: Position,useClass: PositionService}
 ],directives:[
 addgroup,Confirm,editgroup
 ],precompile: [
 ConfirmPopover
 ],}
)
export class group {
 @ViewChild('addGroupModal') addgroupmodal:addgroup;
 @ViewChild('editGroupModal') editgroupmodal:editgroup;
 groupdto:groupDto[];
 subscription:any;

 private data:Array<any> ;

 constructor(private groupservice:groupservice) {
 //this.length = this.data.length;  }
onAdd()
{
 this.addgroupmodal.open();
}
 onEdit(id:string){
 this.editgroupmodal.open(id);
 }
 ngOnInit() {
 this.groupservice.getGroupList().subscribe(p=> {
 this.groupdto = p;
 });

 this.subscription = this.groupservice.isSubmit.subscribe(status=> {
 if (status) {
 this.groupservice.getGroupList().subscribe(p=> {
 this.groupdto = p
 });
 }

 });
 //this.onChangeTable(this.config);  }

 ngOnDestroy() {
 this.subscription.unsubscribe();
 }

 onDel(id:string) {

 this.groupservice.delGroup(id);
 }

}

此处有一点复杂,在该组件中我使用了Modal窗口(单独的一个组件),即在新增、修改时弹出窗口进行数据编辑,同时在删除时我增加提示信息,确认后才能实际进行删除操作。

Template

模板使用了单独的html文件

<div>
 <div class="btn-group">
 <button type="button" class="btn btn-default" (click)="onAdd()">新增部门</button>

 </div>
 <div>
<table class=" table table-striped table-bordered dataTable">
 <thead>
 <tr>
 <th>序号</th>
 <th >
 单位编号
 </th>
 <th>
 单位名称
 </th>
 <th>
 排序号
 </th>
 <th>
 操作
 </th>
 </tr>
 </thead>
 <tbody>
 <tr *ngFor="let item of groupdto ; let i = index">
 <td>{{i+1}}</td>
<td>{{item.GROUPCODE}}</td>
 <td>{{item.GROUPNAME}}</td>
 <td>{{item.NORDER}}</td>
 <td>
 <button type="button" class="btn-danger"  mwl-confirm
 title="提示"  message="您确定要删除吗"  confirmText="确定"  cancelText="取消"  placement="left"  (confirm)="onDel(item.ID)"  (cancel)="cancelClicked = true"  confirmButtonType="danger"  cancelButtonType="default"  ><i class="icon-remove"></i></button>
 <button type="button" class="btn-info" (click)="onEdit(item.ID)"><i class="icon-edit-sign"></i></button>
 </td>
 </tr>
 </tbody>
</table>
 </div>

</div>
<div>
 <add-group #addGroupModal></add-group>
</div>
<div>
 <edit-group #editGroupModal></edit-group>
</div>

provider

providers中我引入了前面创建的服务,由于这是父组件在此处引入后,子组件在注入时就无需再引入groupservice,当然也可以在入口的bootstrap中注入,这样就无需再providers中引入了,具体差异见前面的学习资料。下面的ConfirmOptions和PositionService等都是用于提示框使用的服务。

Directives

在模板中使用了两个子组件(add-groupedit-group)所以需要在Directives中声明。

数据获取

本例中在组件加载时会调用groupsevice获取数据并加载,所以需要在ngOnInit中调用服务获取数据,同时订阅groupsevice中的isSubmit在其更新后再次调用服务获取数据以保障数据同步显示

数据更新

这里使用了@ViewChild('addGroupModal') addgroupmodal:addgroup;

其中@ViewChild('addGroupModal') 与我们在模板中定义的子组件标签<add-group#addGroupModal></add-group>保持一致。
通过ViewChild的定义,下面我们就能使用子组件的方法弹出窗口。

onEdit(id:string){
this.editgroupmodal.open(id);
}

子组件

/** * Created by Administrator on 2016-07-11. */ import {Component,ViewChild} from "@angular/core";
import {groupservice} from "./group.Service";
import {FormBuilder,Control,Validators,ControlGroup} from "@angular/common";
import {groupDto} from "./models/groupDto";
import {MODAL_DIRECTIVES} from "../components/modal/ng2-bs3-modal";
import {ModalComponent} from "../components/modal/components/modal";
@Component({
 selector:"edit-group",templateUrl:"./app/curd/editgroup.html",directives: [MODAL_DIRECTIVES,ModalComponent ]
})
export class editgroup{
 groupdto:groupDto;
 groupCode:Control;
 groupName:Control;
 norder:Control;
 form: ControlGroup;
 subscription: any;
 constructor(private groupservice:groupservice,private builder: FormBuilder) {
 var obj={ID:"1",GROUPCODE:"",GROUPNAME:"",NORDER:1,PARENTID:"",GROUPTYPE:""};
 this.groupdto=obj;
 this.groupCode = new Control('',Validators.compose([Validators.required,Validators.maxLength(10)]));
 this.groupName = new Control('',Validators.maxLength(20)]));
 this.norder=new Control('',Validators.required);
 this.form= builder.group({
 groupCode: this.groupCode,groupName: this.groupName,norder: this.norder  });
 }
 @ViewChild('myModal') modal: ModalComponent;

 close() {
 this.modal.close();
 }

 open(id:string) {
 this.groupservice.getGroup(id).subscribe(p=>{
 this.groupdto=p;
 })
 this.modal.open();
 }
 onSubmit(event){
 this.groupservice.editGroup(this.groupdto.ID,this.groupdto);
 this.modal.close();
 }
 ngOnInit(){

 this.subscription=this.groupservice.isSubmit.subscribe();


 }
 ngOnDestroy(){
 this.subscription.unsubscribe();
 }
}

模板

<modal #myModal>
 <modal-header>
 <h4 class="modal-title">编辑单位</h4>
 </modal-header>
 <modal-body>
 <form [ngFormModel]="form" (submit)="onSubmit(planetform.value)" #planetform="ngForm">
 <div class="form-group" >
 <label for="inputGroupCode">单位编号</label>
 <input type="text" class="form-control" id="inputGroupCode" placeholder="单位编号" ngControl="groupCode"  [(ngModel)]="groupdto.GROUPCODE"  >
 <div [hidden]="groupCode.valid || groupCode.pristine" class="alert alert-danger">
 单位编码不能为空或长度不能超过10个字符
 </div>

 </div>
 <div class="form-group">
 <label for="inputGroupName">单位名称</label>
 <input type="text" class="form-control" id="inputGroupName" placeholder="单位名称" ngControl="groupName"  [(ngModel)]="groupdto.GROUPNAME"  >
 <div [hidden]="groupName.valid || groupName.pristine" class="alert alert-danger">
 单位名称不能为空或长度不能超过20个字符
 </div>
 </div>
 <div class="form-group">
 <label for="exampleInputFile">排序码</label>
 <input type="number" id="exampleInputFile" ngControl="norder" [(ngModel)]="groupdto.NORDER">
 </div>

 <button type="submit" class="btn btn-primary" [disabled]="!form.valid">提交</button>
 </form>
 </modal-body>
 <modal-footer>

 <button type="button" class="btn btn-primary" (click)="modal.close()">关闭</button>
 </modal-footer>
</modal>

这里可以看到使用的是bootstrap中的modal,所以注意要在首页html中要引入bootstrap及jquery。

在这个子组件中使用From中使用了数据验证,如果验证不通过([disabled]="!form.valid")则提交按钮不能使用。

<button type="submit" class="btn btn-primary" [disabled]="!form.valid">提交</button>

Form使用

此例中使用的angular2的formbuilder方式建立表单,所以需要在构造函数中注入

this.groupCode = new Control('',Validators.maxLength(10)]));

这里定义的groupCode使用了组合验证,与下面input中的ngControl名称一致,ngModel绑定的是实例化的Dto

<input type="text" class="form-control" id="inputGroupCode" placeholder="单位编号" ngControl="groupCode" [(ngModel)]="groupdto.GROUPCODE" >


最后上图片


猜你在找的Angularjs相关文章