背景需求:
- 1.項目開發(fā)、測試敞映、發(fā)布使用的后臺發(fā)布接口均不一致禾怠,根據(jù)不同環(huán)境配置接口的host+port
- 2.全局處理非正確的response
- 3.每次請求前顯示loading,請求后隱藏loading(本文不涉及)
實現(xiàn):
-
1.自定義HttpInterceptorService(http.interceptor.service.ts)
import { Injectable } from '@angular/core'; import { Http, Request, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend, Headers } from '@angular/http'; import 'rxjs/Rx'; import { Observable } from 'rxjs/Observable'; @Injectable() export class HttpInterceptorService extends Http { status = { "status.400": "錯誤的請求尤蒿。由于語法錯誤,該請求無法完成幅垮。", "status.401": "未經(jīng)授權(quán)腰池。服務(wù)器拒絕響應(yīng)。", "status.403": "已禁止忙芒。服務(wù)器拒絕響應(yīng)示弓。", "status.404": "未找到。無法找到請求的位置呵萨。", "status.405": "方法不被允許奏属。使用該位置不支持的請求方法進行了請求。", "status.406": "不可接受潮峦。服務(wù)器只生成客戶端不接受的響應(yīng)囱皿。", "status.407": "需要代理身份驗證∨芎迹客戶端必須先使用代理對自身進行身份驗證铆帽。", "status.408": "請求超時。等待請求的服務(wù)器超時德谅。", "status.409": "沖突爹橱。由于請求中的沖突,無法完成該請求。", "status.410": "過期愧驱。請求頁不再可用慰技。", "status.411": "長度必需。未定義“內(nèi)容長度”组砚。", "status.412": "前提條件不滿足吻商。請求中給定的前提條件由服務(wù)器評估為 false。", "status.413": "請求實體太大糟红。服務(wù)器不會接受請求艾帐,因為請求實體太大。", "status.414": "請求 URI 太長盆偿。服務(wù)器不會接受該請求柒爸,因為 URL 太長。", "status.415": "不支持的媒體類型事扭。服務(wù)器不會接受該請求捎稚,因為媒體類型不受支持。", "status.416": "HTTP 狀態(tài)代碼 {0}", "status.500": "內(nèi)部服務(wù)器錯誤求橄。", "status.501": "未實現(xiàn)今野。服務(wù)器不識別該請求方法,或者服務(wù)器沒有能力完成請求罐农。", "status.503": "服務(wù)不可用条霜。服務(wù)器當前不可用(過載或故障)。" }; constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { super(backend, defaultOptions); } request(url: string | Request, options ? : RequestOptionsArgs): Observable < Response > { //console.log("before..."); //根據(jù)不同的生產(chǎn)環(huán)境配置http前綴 typeof url=='string'? (url='http://192.168.1.205:8099/'+url):(url.url='http://192.168.1.205:8099/'+url.url); return this.intercept(super.request(url, options)); } get(url: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.get(url, options)); } post(url: string, body: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.post(url, body, this.getRequestOptionArgs(options))); } put(url: string, body: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.put(url, body, this.getRequestOptionArgs(options))); } delete(url: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.put(url, this.getRequestOptionArgs(options))); } getRequestOptionArgs(options ? : RequestOptionsArgs): RequestOptionsArgs { if (options == null) { options = new RequestOptions(); } if (options.headers == null) { options.headers = new Headers(); } options.headers.append('Content-Type', 'application/json'); return options; } intercept(observable: Observable < Response > ): Observable < Response > { //console.log("after..."); return observable.catch((err, source) => { if (err.status<200 || err.status>=300) { alert('網(wǎng)絡(luò)錯誤:'+err.status+' - '+this.status['status.'+err.status]); return Observable.empty(); } else { return Observable.throw(err); } }); } }
-
2.在app.module.ts中provide
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { Http, HttpModule, XHRBackend, RequestOptions } from '@angular/http'; import { RouterModule, Routes } from '@angular/router'; import { MessagesModule, GrowlModule, ConfirmDialogModule, ConfirmationService, DialogModule, BlockUIModule } from 'primeng/primeng'; import { AppComponent } from './app.component'; import { HttpInterceptorService } from './shared/http.interceptor.service'; export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions){ let service = new HttpInterceptorService(xhrBackend, requestOptions); return service; } @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(appRoutes), LoginModule, FrameModule, MessagesModule, GrowlModule, ConfirmDialogModule, DialogModule, BlockUIModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: [ HttpInterceptorService, { provide: Http, useFactory: interceptorFactory, deps: [XHRBackend, RequestOptions] } ] }) export class AppModule { }
-
3.使用涵亏,示例:app.component.ts
import { Component } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; constructor(private http: Http){} ngOnInit(){ this.http.get('api/user/functions') .toPromise() .then(res => console.log(res)); } }