以前看到angular2正式發佈了,過去看了下,感受不錯,因而入坑。
使用過程當中想寫一個像angular1那樣的攔截器,一路坎坷啊css
.factory('HttpRequestInterceptor', ['$q', '$injector', 'ConfigService', 'DialogService', function($q, $injector, ConfigService, DialogService) { return { request: function(config) { if (config.method === 'POST') { config.timeout = 60000; if (config.data === undefined) { config.data = { nologin: 999 }; } else { config.data.nologin = 999; } } return config; }, requestError: function(rejection) { DialogService.alert('發送請求失敗,請檢查網絡'); return $q.reject(rejection); }, response: function(resp) { if (resp.data.code !== undefined && resp.data.code !== 0) { if (resp.data.code === 5003) { var stateService = $injector.get('$state'); stateService.go('login', {}, { reload: true }); } else { DialogService.alert(resp.data.msg); } } return resp; }, responseError: function(rejection) { console.log(rejection); if (rejection.status === 0) { DialogService.alert('請求響應錯誤,請檢查網絡'); } else if (rejection.status === 500) { DialogService.alert('服務器出錯'); } else { DialogService.alert('請求失敗,請檢查網絡'); } return $q.reject(rejection); } }; }])
去Stackoverflow上搜了很久,有相關內容是不錯,但過期了。不過思路仍是能夠借鑑的。html
@Injectable() export class CustomHttp extends Http { constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { super(backend, defaultOptions); } request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { console.log('request...'); return super.request(url, options).catch(res => { // do something }); } get(url: string, options?: RequestOptionsArgs): Observable<Response> { console.log('get...'); return super.get(url, options).catch(res => { // do something }); } }
app.module.ts裏寫法過期了github
bootstrap(AppComponent, [HTTP_PROVIDERS, new Provider(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions), deps: [XHRBackend, RequestOptions] }) ]);
按照上述代碼,寫法與angular2 r6不一樣,不知道怎麼改。繼續搜索,發現大部分寫法都雷同,只是注入方式不一樣,後面看到了r6的注入方式,折騰幾回,有告終果web
customhttp.tsjson
import { Injectable } from '@angular/core'; import { Http, Request, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend, Headers } from '@angular/http'; import 'rxjs/Rx'; import { Observable } from 'rxjs/Observable'; import { PubSubService } from './shared/pubsub.service'; @Injectable() export class CustomHttp extends Http { _pubsub: PubSubService; constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, pubsub: PubSubService) { super(backend, defaultOptions); this._pubsub = pubsub; } request(url: string | Request, options ? : RequestOptionsArgs): Observable < Response > { console.log("good"); 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 > { this._pubsub.beforeRequest.emit("beforeRequestEvent") observable.subscribe(null, (err) => { console.log('err'); this._pubsub.afterRequest.emit("afterRequestEvent"); this.handleError(err.status); }, () => { console.log('complete'); this._pubsub.afterRequest.emit("afterRequestEvent"); }); return observable; } handleError(status) { if (status === 0) { this._pubsub.errorToast.emit("請求響應錯誤,請檢查網絡"); } else if (status === 404) { this._pubsub.errorToast.emit("請求連接不存在,請聯繫管理員"); } else if (status === 500) { this._pubsub.errorToast.emit("服務器出錯,請稍後再試"); } else { this._pubsub.errorToast.emit("未知錯誤,請檢查網絡"); } } }
pubsup.service.tsbootstrap
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; // 發佈訂閱事件, 繼承自Subject, emit用於發射事件 class PubSubEvent extends Subject < String > { constructor() { super(); } emit(value) { super.next(value); } } @Injectable() export class PubSubService { beforeRequest: PubSubEvent; afterRequest: PubSubEvent; errorToast: PubSubEvent; successToast: PubSubEvent; showPupup: PubSubEvent; hidePupup: PubSubEvent; confirm: PubSubEvent; constructor() { this.beforeRequest = new PubSubEvent(); this.afterRequest = new PubSubEvent(); this.errorToast = new PubSubEvent(); this.successToast = new PubSubEvent(); this.showPupup = new PubSubEvent(); this.hidePupup = new PubSubEvent(); this.confirm = new PubSubEvent(); } }
app.module.tsapi
import { NgModule, Injectable } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http'; // import { InMemoryWebApiModule } from 'angular-in-memory-web-api'; import { HeroData } from './hero/hero-data'; import { routing } from './app.routing'; import { AppComponent } from './app.component'; import { CrisisCenterComponent } from './crisis/crisis-center.component'; import { MapComponent } from './map/map.component'; import { CustomHttp } from './customhttp'; import { MapService } from './map/map.service'; import { PubSubService } from './shared/pubsub.service'; import { PubSubComponent } from './shared/pubsub.component'; @NgModule({ declarations: [ AppComponent, CrisisCenterComponent, MapComponent, PubSubComponent ], imports: [ BrowserModule, FormsModule, HttpModule, // InMemoryWebApiModule.forRoot(HeroData), routing ], providers: [ MapService, PubSubService, { provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, pubsub: PubSubService) => new CustomHttp(backend, defaultOptions, pubsub), deps: [XHRBackend, RequestOptions, PubSubService] } ], bootstrap: [AppComponent], }) export class AppModule {}
最後是pubsup.component.ts,我是將loading, toast, pupup放在了一塊兒
loading將在每一個請求前顯示,請求失敗或結束隱藏
toast將在請求失敗顯示2秒鐘,或者在其餘組件裏調用
pupup將在刪除事件前提問,想放在delete api裏自動顯示並處理,可是沒有實現
具體代碼在我github:https://github.com/jiangbo201...服務器
import { Component, Input } from '@angular/core'; import { Http } from '@angular/http'; import { PubSubService } from './pubsub.service'; @Component({ selector: 'app-pubsub', templateUrl: './pubsub.component.html', styleUrls: ['./pubsub.component.css'] }) export class PubSubComponent { showloading = false; showPupub = false; showSuccessToast = false; showErrorToast = false; errorValue: any = "error"; successValue: any = "success"; _pubsub: PubSubService; constructor(public http: Http, public pubsub: PubSubService) { this._pubsub = pubsub; } cancel() { this.showPupub = false; } confirm() { this.showPupub = false; this._pubsub.confirm.emit("confirm"); } ngOnInit() { this._pubsub.beforeRequest.subscribe(data => { console.log(data); this.showloading = true; }); this._pubsub.afterRequest.subscribe(data => { console.log(data); this.showloading = false; }); this._pubsub.errorToast.subscribe(data => { console.log(data); this.showErrorToast = true; this.errorValue = data; let that = this; // setTimeout(function() { // console.log(this); // that.showErrorToast = false; // }, 2000); }); this._pubsub.successToast.subscribe(data => { console.log(data); this.showSuccessToast = true; this.successValue = data; let that = this; setTimeout(function() { that.showSuccessToast = false; }, 2000); }); this._pubsub.showPupup.subscribe(data => { this.showPupub = true; console.log(data); }); this._pubsub.hidePupup.subscribe(data => { console.log(data); this.showPupub = false; }); } }
最後,我想在每一個刪除aip裏自動攔截,並彈出提示,若是肯定刪除就執行,若是放棄就return
可是不知道怎麼阻塞執行,歡迎交流restful