關于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; }   });}這步就是將已經刪除的數據從本地數組中過濾掉
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答