沒錯啦,Angular 也有 Service,本篇將針對其作說明
它們也是遵循 ES2015 的 module 產出的類別
ng generate service stocks.service
以下是這個 service 的內容:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
let stocks: Array<string> = ['AAPL', 'GOOG' ,'FB' ,'AMZN','TWTR'];
let service: string = 'https://angular2-in-action-api.herokuapp.com';
export interface StockInterface {
symbol: string;
lastTradePriceOnly: number;
change: number;
changeInPercent: number;
}
@Injectable({})
export class StocksService {
constructor(private http: HttpClient) { }
get() {
return stocks.slice();
}
add(stock: string) {
stocks.push(stock);
}
remove(stock: string) {
stocks.splice(stocks.indexOf(stock), 1);
}
load(symbols: Array<string>) {
if(symbols) {
return this.http.get<Array<StockInterface>>(service + '/stocks/snapshot?symbols=' + symbols.join());
}
}
}
定義好了 Service,還要 import 並註冊它,所以:
import { HttpClientModule } from '@angular/common/http';
import { StocksService } from './services/stocks.service';
接著在 NgModule 提供的資訊中要填上以下:
imports 的陣列中補上 HttpClientModule,這樣才能使用其內含的 HttpClient
providers 的陣列中補上 StockService
完整的 app.module.ts 如下:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StocksService } from './services/stocks.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [StocksService],
bootstrap: [AppComponent]
})
export class AppModule { }
相信到這裡大家都暈了,小結一下: