摘要:本文将带你了解使用http模块,希望本文对大家学WebApp有所帮助。
前台源码
后台源码
说明:后台代码是用asp.net编写的
前言
之前写了那么多,不过都是静态页面。现在使用http模块与后端通信,变可以让我们的应用活起来。
我把后台服务写成了可跨域请求的webapi,这样在node上面调试起来就方便多了。
创建服务模块
nggserviceaccount
ng给我们创建的模块account.service.ts,内容如下。
有关@Injectable和@Component,都是angular中的关键字或者关键注解。通过注解来表明js文件的类型,以方便angular框架进行调用。
@Component表示该js文件所导出的类是组件。
@Injectable表示该js文件所导出的文件是服务,而服务是可以通过注入来创建的。
服务的注入,是angular中用来剥离controller和业务逻辑的方式。
import{Injectable}from'@angular/core';
@Injectable()
exportclassAccountService{
constructor(){}
}
添加一个方法
getBillTypes(){
console.log('这是service里的方法');
}
引用服务
在accounting.component.ts里引用
import{AccountService}from'../account.service';
@NgModule({
providers:[
AccountService
],
})
推荐使用依赖注入的方式
constructor(privateservice:AccountService){
service.getBillTypes();//调用方法
}
查看下效果,提示错误。
UnhandledPromiserejection:NoproviderforAccountService!;Zone:angular;Task:Promise.then;Value:
原来是在app.module.ts里面也要添加引用
import{AccountService}from'./account.service';
providers:[AccountService],
这下就完成了简单了例子。ng的编程风格越来越像我们使用的c#,java等的编程风格。当然编程思想也是越来越和我们后台开发相似了。
整理下我们的后台接口
添加一个Model文件夹,在下面添加一个model.url.ts文件来存储我们的接口信息
consthost='//127.0.0.1:8001';
exportconstUrls={
GetBillTypes:host+'/api/bill/getbilltypes',//获取记账类型
GetBills:host+'/api/bill/GetBills',//获取列表
GetCount:host+'/api/bill/GetCount',//获取统计信息
GetTotallCount:host+'/api/bill/GetTotallCount',//获取求和数据
AddBills:host+'/api/bill/AddBills',//添加记账信息
DeleteBill:host+'/api/bill/DeleteBill',//删除记账信息
};
在我们的service中引入
import{Urls}from'./Model/model.url';
整理方法
exportclassAccountService{
privateurls=Urls;
constructor(){}
getBillTypes():void{
console.log(this.urls.GetBillTypes);
}
GetBills():void{
console.log(this.urls.GetBills);
}
GetCount():void{
console.log(this.urls.GetCount);
}
GetTotallCount():void{
console.log(this.urls.GetTotallCount);
}
AddBills():void{
console.log(this.urls.AddBills);
}
DeleteBill():void{
console.log(this.urls.DeleteBill);
}
}
使用http模块
在我们的app.module.ts中已经引入了
import{HttpModule}from'@angular/http';
我们要在account.service.ts中引入
import{Http}from'@angular/http';
import'rxjs/add/operator/toPromise';
构造函数中注入依赖
constructor(privatehttp:Http){}
修改getBillTypes方法试试,看请求返回数据和http.get返回的是什么。
getBillTypes(){
console.log(this.urls.GetBillTypes);
constdata=this.http.get(this.urls.GetBillTypes)
.toPromise()
.then(response=>console.log(response));
console.log(data);
}
http.get(url)(或者postputdelete),访问服务器以后会返回一个observation对象,事实上是observation<服务器返回值>。通过toPromise转换成promise对象以后,就可以正常的使用then方法去处理返回值了。
通过promise的then方法,可以获得到服务器的返回值。个返回值都是json字符串,而在angular还是先按字符串处理。调用字符串的.json()方法转化为json数组或者json对象,继续调用关键字as将json数组或者json对象转化类,转化的方式是属性对应。
因此我们修改方法,在model文件夹下添加自定义的Result类型,
//接口返回数据格式
exportclassResult{
error:any;//错误时返回的信息
result:any;//成功时返回的数据
success:boolean;//是否成功
}
在account.service.ts中引入并修改方法
import{Result}from'./Model/model.result';
getBillTypes():Promise
returnthis.http.get(this.urls.GetBillTypes)
.toPromise()
.then(response=>response.json()asResult)
.catch(this.handleError);
}
在accounting.component.ts中修改调用的方法
constructor(privateservice:AccountService){
service.getBillTypes().then(r=>{console.log(r);});
}
这正是我们后台返回的数据且是json格式的。
这里我们用到了自定义类型Result的作用呢,看控制台打印的数据,对数据没什么影响,但是对我写代码是有帮助的。看下面:
对,会提示,如果使用了类型里没有的字段,还会报错。这活生生把一个弱类型语言变成了强类型的。当然如果不喜欢,我们可以不用自定义类。把自定义的Result换成any即可。
完善service
添加三个自定义类型
//记账类型的数据结构
exportclassBillType{
name:string;
fontStyle:string;
id:number;
}
//记账的数据结构
exportclassBill{
id:number;
creationTime:string;
money:number;
name:string;
fontStyle:string;
BillTypeId:number;
}
要细分就太多了,大致分成这几类吧,引入并完善我们的方法
exportclassAccountService{
privateurls=Urls;
constructor(privatehttp:Http){}
getBillTypes():Promise
returnthis.get(this.urls.GetBillTypes);
}
GetBills(date,skipCount,user):Promise
constd=newURLSearchParams();
d.set('date',date);
d.set('skipCount',skipCount);
d.set('user',user);
returnthis.get(this.urls.GetBills,d);
}
GetCount(date:string,type:number,user:string,GroupBy=0):Promise
constd=newURLSearchParams();
d.set('date',date);
d.set('type',type.toString());
d.set('user',user);
d.set('GroupBy',GroupBy.toString());
returnthis.get(this.urls.GetCount,d);
}
GetTotallCount(user):Promise
returnthis.get(this.urls.GetTotallCount+'?user='+user);
}
AddBills(data):Promise
returnthis.post(this.urls.AddBill,data);
}
DeleteBill(data:number):Promise
returnthis.post(this.urls.DeleteBill,data);
}
//对get请求进行封装
privateget(url:string,data:URLSearchParams=null):Promise
returnthis.http.get(url,{search:data})
.toPromise().then(r=>r.json()asResult)
.catch(this.handleError);
}
//对post请求进行封装
privatepost(url:string,data:any):Promise
returnthis.http.post(url,data)
.toPromise().then(r=>r.json()asResult)
.catch(this.handleError);
}
//捕获异常并输出
privatehandleError(error:any):Promise
console.error('Anerroroccurred',error);
returnPromise.reject(error.message||error);
}
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之WebApp频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号