HttpInterceptor
用來攔截所有的 request 與 response
要怎麼建立 HttpInterceptor?
ng g s services/interceptor
接著我們就來填入內容吧:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { HttpEvent, HttpInterceptor, HttpResponse, HttpHandler, HttpRequest } from '@angular/common/http';
import { AccountService } from './account.service';
import { Stock } from './stocks.model';
import { ConfigService } from './config.service';
@Injectable()
export class StocksInterceptor implements HttpInterceptor {
constructor(private accountService: AccountService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const request = req.clone();
request.headers.append('Accept', 'application/json');
return next.handle(request).do(event => {
if (event instanceof HttpResponse && event.url === ConfigService.get('api')) {
const stocks = event.body as Array<Stock>;
let symbols = this.accountService.stocks.map(stock => stock.symbol);
stocks.forEach(stock => {
this.accountService.stocks.map(item => {
if (stock.symbol === item.symbol) {
item.price = stock.price;
item.change = ((stock.price * 100) - (item.cost * 100)) / 100;
}
});
});
this.accountService.calculateValue();
return stocks;
}
});
}
}
定義好 Interceptor,要在哪注入呢? 其實注入在哪都不對,正確的方式是讓 AppModule 認得這它
修改 app.module.ts 如下
// ...(略)
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
// ...(略)
@NgModule({
// ...(略)
providers: [
// ...(略)
{
provide: HTTP_INTERCEPTORS,
useClass: StocksInterceptor,
multi: true
},
// ...(略)
],
bootstrap: [AppComponent]
})
export class AppModule { }
export const interceptorProviders =
[
{ provide: HTTP_INTERCEPTORS, useClass: RequestTimestampService, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AjaxBusyIdentifierInterceptorService, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorService, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: XML2JsonInterceptorService, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorNotifierService, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: RetryInterceptorService, multi: true }
];
Helper Services
主要處理一些非商業邏輯的共用性質的演算法,比方說排序, 解析...等
這些 Helper 大部份不會一開始就存在,而是在開發的過程中慢慢發現,似乎很多地方都有用到相似的邏輯的時候,再抽出來
跟一般的 service 差不多,都是為了讓 component 中的邏輯不要過於複雜,使其能專注在 UI 的呈現上
以下的範例就是一個方便管理 localStorage 的 Helper
import { Injectable } from '@angular/core';
@Injectable()
export class LocalStorageService {
get(key: string, fallback: any) {
let value = localStorage.getItem(key);
return (value) ? JSON.parse(value) : fallback;
}
set(key: string, value: any) {
localStorage.setItem(key, JSON.stringify(value));
}
}
小結:
When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.
評論