详解AngularJS2 Http服务
关于http服务
HttpModule并不是angular的核心模块,它是一个附加的模块,存在于@angular/http中,虽然如此但是依然可以在需要的时候使用它,只需要在使用之前引入即可。对于大多数app来说使用http服务是很常见的,所以我们将HttpModule加入到AppModule的import列表和应用的根组件中,这样就可以在整个应用中使用http服务了
在自定义服务中使用Http服务
http服务通过其get方法获取数据,他会返回RxJSObservable,我们希望使用的数据是Promise,然而Observable并没有toPromise()方法,可以在自定义服务中这样引入
import'rxjs/add/operator/toPromise';
如此就拓展了Observable的功能了
具体代码如下
import{Injectable}from'@angular/core'; import{Headers,Http}from'@angular/http'; import'rxjs/add/operator/toPromise'; import{Hero}from'./hero'; privateheroesUrl='api/heroes';//URLtowebapi constructor(privatehttp:Http){} getHeroes():Promise{ returnthis.http.get(this.heroesUrl) .toPromise() .then(response=>response.json().dataasHero[]) .catch(this.handleError); } privatehandleError(error:any):Promise { console.error('Anerroroccurred',error);//fordemopurposesonly returnPromise.reject(error.message||error); }
在回调函数then()中调用了返回对象的json()方法将data从返回对象中分离出来
.then(response=>response.json().dataasHero[])
这里的.data是因为返回对象中有data这个属性,具体情况下会不一样
注意:Httpfailure是经常发生的,必须预料到会有异常的可能,所以在方法最后捕获了异常并将其传递给异常处理器,使用Promise.reject()将错误信息返回给服务调用者
利用服务实现数据的增删改查
信息查询
可以在请求url里面带上参数,这样就可以将参数传到后台,服务器查到信息后返回到前台
getHero(id:number):Promise{ consturl=`${this.heroesUrl}/${id}`; returnthis.http.get(url).toPromise() .then(response=>response.json().dataasHero) .catch(this.handleError); }
修改信息
在自定义服务中
privateheaders=newHeaders({'Content-Type':'application/json'}); update(hero:Hero):Promise{ consturl=`${this.heroesUrl}/${hero.id}`; returnthis.http .put(url,JSON.stringify(hero),{headers:this.headers}) .toPromise() .then(()=>hero) .catch(this.handleError); }
依然是在url后带上id告知服务器要修改的记录标识,JSON.stringify()将对象转化成json字符串,通过put将字符串放到请求中,header说明了请求体的类型
在调用服务的组件中
save():void{ this.heroService.update(this.hero) .then(()=>this.goBack()); }
修改成功后返回前一个视图
添加信息
在自定义服务中
create(name:string):Promise{ returnthis.http .post(this.heroesUrl,JSON.stringify({name:name}),{headers:this.headers}) .toPromise() .then(res=>res.json().data) .catch(this.handleError); }
删除信息
在自定义服务中
delete(id:number):Promise{ consturl=`${this.heroesUrl}/${id}`; returnthis.http.delete(url,{headers:this.headers}) .toPromise() .then(()=>null) .catch(this.handleError); }
这步只是将后台的信息删除了,但是本地数组中依然存在,所以依然会在视图中显示,所以就要在组建中进行一些处理
delete(hero:Hero):void{ this.heroService .delete(hero.id) .then(()=>{ this.heroes=this.heroes.filter(h=>h!==hero); if(this.selectedHero===hero){this.selectedHero=null;} }); }
这步就是将已经删除的数据从本地数组中过滤掉
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。