当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 详解AngularJS2 Http服务

详解AngularJS2 Http服务

2017年12月12日  | 移动技术网IT编程  | 我要评论

关于http服务

httpmodule并不是angular的核心模块,它是一个附加的模块,存在于@angular/http中,虽然如此但是依然可以在需要的时候使用它,只需要在使用之前引入即可。对于大多数app来说使用http服务是很常见的,所以我们将httpmodule加入到appmodule的import列表和应用的根组件中,这样就可以在整个应用中使用http服务了

在自定义服务中使用http服务

http服务通过其get方法获取数据,他会返回rxjs observable,我们希望使用的数据是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';
 private heroesurl = 'api/heroes'; // url to web api

 constructor(private http: http) { }

 getheroes(): promise<hero[]> {
  return this.http.get(this.heroesurl)
        .topromise()
        .then(response => response.json().data as hero[])
        .catch(this.handleerror);
 }

 private handleerror(error: any): promise<any> {
  console.error('an error occurred', error); // for demo purposes only
  return promise.reject(error.message || error);
 }

在回调函数then()中调用了返回对象的json()方法将data从返回对象中分离出来

.then(response => response.json().data as hero[])

 这里的.data是因为返回对象中有data这个属性,具体情况下会不一样

注意:http failure是经常发生的,必须预料到会有异常的可能,所以在方法最后捕获了异常并将其传递给异常处理器,使用promise.reject()将错误信息返回给服务调用者

利用服务实现数据的增删改查

信息查询

可以在请求url里面带上参数,这样就可以将参数传到后台,服务器查到信息后返回到前台

  gethero(id: number): promise<hero> {
    const url = `${this.heroesurl}/${id}`;
    return this.http.get(url).topromise()
   .then(response => response.json().data as hero)
   .catch(this.handleerror);
  }

修改信息

在自定义服务中

  private headers = new headers({'content-type': 'application/json'});
  update(hero: hero): promise<hero> {
  const url = `${this.heroesurl}/${hero.id}`;
  return this.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<hero> {
 return this.http
  .post(this.heroesurl, json.stringify({name: name}), {headers: this.headers})
  .topromise()
  .then(res => res.json().data)
  .catch(this.handleerror);
}

删除信息

在自定义服务中

  delete(id: number): promise<void> {
   const url = `${this.heroesurl}/${id}`;
   return this.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; }
   });
}

这步就是将已经删除的数据从本地数组中过滤掉

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网