Angular4 開發(fā)實戰(zhàn):(7) 創(chuàng)建服務(wù)(Service)

2018-06-19 11:24 更新
服務(wù)一般用來放置可復(fù)用的代碼。
下面我們創(chuàng)建一個管理書籍的服務(wù):

ng g service book

自動生成的基礎(chǔ)模板:

import { Injectable } from '@angular/core';   


@Injectable()  

export class BookService {    

  constructor() { }   

}

建議每一個服務(wù)都加上@Injectable()裝飾器。 注意: 當 TypeScript 看到@Injectable()裝飾器時,就會記下本服務(wù)的元數(shù)據(jù)。 如果 Angular 需要往這個服務(wù)中注入其它依賴,就會使用這些元數(shù)據(jù)。 現(xiàn)在我們添加一個獲取書籍列表的方法:

export class BookService {   

  getBooks() {}  

}

我們使用Http來從服務(wù)器獲取數(shù)據(jù),但使用前需要注冊入:

// app.module.ts   

import { HttpModule } from '@angular/http';   


@NgModule({   

  ...   

  imports: [   

    ...   

    HttpModule   

  ],   

  providers: [],   

  bootstrap: [AppComponent]  

})

我在這里模擬一個書籍書籍,創(chuàng)建一個book.json

{   

  "books": [   

    {   

      "name": "HTML"   

    },      

    {   

      "name": "Javascript"   

    },   

   {   

     "name": "Angular"   

   }   

  ]  

}

接下來修改一下book.service.ts

import { Injectable } from '@angular/core';  

import {Http} from '@angular/http';  

import 'rxjs/add/operator/toPromise';   


@Injectable()  

export class BookService {    

  constructor(private http: Http) { }    

  

  getBooks() {

    const url = '/src/app/service/book.json'; 

    return this.http.get(url)   

           .toPromise()   

           .then(res => res.json())   

           .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);   

  }  

}

注:默認情況下,Angular 的Http服務(wù)返回一個 RxJS 的Observable對象。 我們可以通過toPromise()方法將其轉(zhuǎn)為便捷的承諾Promise。 使用toPromise()方法時要引入:

import 'rxjs/add/operator/toPromise';

接下來我們要使用這個BookService服務(wù)了:

// demo-service.service.ts   

import { Component, OnInit } from '@angular/core';  

import {BookService} from '../../service/book.service';   


@Component({   

  ...   

  providers: [BookService]    

})  


export class DemoServiceComponent implements OnInit {    


  books: any[];   

  constructor(private bookService: BookService) { }    


  ngOnInit() {   

    this.bookService.getBooks()   

    .then(res => {   

      this.books = res.books;   

    });   

  }  

}   


// demo-service.component.html   

<li *ngFor="let book of books">{{book.name}}</li>

在上面的代碼中,我們做了三步工作: 1. 將BookService服務(wù)添加到@Component組件的元數(shù)據(jù)底部添加providers數(shù)組屬性中。 2. 將BookService注入到構(gòu)造方法中,并定義了一個私有屬性bookService。 3. 在OnInit()生命鉤子函數(shù)中調(diào)用服務(wù)并獲取書籍數(shù)據(jù) 注:
  • providers數(shù)組告訴 Angular,當它創(chuàng)建新的DemoServiceComponent組件時,也要創(chuàng)建一個BookService的新實例。
  • 盡量不要在構(gòu)造方法中獲取服務(wù)數(shù)據(jù),要在生命鉤子函數(shù)中調(diào)用。
常用服務(wù) 獲取(GET)數(shù)據(jù):

get() {   

  return this.http.get(url)   

         .toPromise()   

         .then(response => response.json() )   

         .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);  

}

新建(POST)數(shù)據(jù):

private headers = new Headers({'Content-type': 'application/json'});   


create() {   

  return this.http   

         .post(url, JSON.stringify(hero), {headers: this.headers})   

         .toPromise()   

         .then(response => response.json())   

         .catch(this.handleError);  

}

更新(update)數(shù)據(jù):

private headers = new Headers({'Content-type': 'application/json'});   


update() {   

  return this.http   

         .put(url, JSON.stringify(hero), {headers: this.headers})   

         .toPromise()   

         .then(response => response.json())   

         .catch(this.handleError);  

}

刪除(DELETE)數(shù)據(jù):

private headers = new Headers({'Content-type': 'application/json'});   


delete() {   

  return this.http

        .delete(url, {headers: this.headers})   

        .toPromise()   

        .then(() => null)   

        .catch(this.handleError);  

}


如發(fā)現(xiàn)任何問題或有好的建議,歡迎在下方評論留言。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號