查看有關ionic2攔截此鏈接:http://roblouie.com/article/354/http-interceptor-in-angular-2/
1 - 覆蓋的Http標準類
import {Injectable} from "@angular/core";
import {Http, RequestOptionsArgs, ConnectionBackend, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {Request} from "@angular/http/src/static_request"
import {Response} from "@angular/http/src/static_response"
@Injectable()
export class CustomHttpInterceptor extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('My new request...');
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('My new get...');
return super.get(url, options);
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
console.log('My new post...');
return super.post(url, body, options);
}
}
2 - 註冊商
export function providers() {
return [
Api,
Items,
User,
Camera,
GoogleMaps,
SplashScreen,
StatusBar,
{ provide: Settings, useFactory: provideSettings, deps: [Storage] },
// Keep this to enable Ionic's runtime error handling during development
{ provide: ErrorHandler, useClass: IonicErrorHandler },
{
provide: Http,
useFactory: (backend:XHRBackend, defaultOptions:RequestOptions) => {
return new CustomHttpInterceptor(backend, defaultOptions);
},
deps: [XHRBackend, RequestOptions]
}
];
}
@NgModule({
declarations: declarations(),
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [Http]
}
}),
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: entryComponents(),
providers: providers()
})
export class AppModule { }
3 - 而只使用Http類,因爲Custom H ttp攔截器實例是自動注入的。
import { Page1 } from '../pages/page1/page1';
import { Page2 } from '../pages/page2/page2';
import { Http } from '@angular/http';
@Component({
templateUrl: 'app.html'
})
export class MyAppComponent {
@ViewChild('content') nav : Nav;
root: any = Page1;
constructor(public platform: Platform, private http: Http) {
this.initializeApp();
http.get('https://google.com');
}
...
這似乎是一個很好的實現。我嘗試過,但我使用CustomHttp中的get()方法時出現此錯誤:ORIGINAL EXCEPTION:TypeError:_get(...)。call(...)。catch不是函數 –
@Chris您需要像這樣導入'catch'運算符:'import'rxjs/add/operator/catch' –
現在這段代碼工作了(並從CustomHttp中移除了構造函數)。但現在我有其他錯誤:原始異常:TypeError:無法讀取包含函數XHRConnection(req,browserXHR,baseResponseOptions){... var _xhr = browserXHR.build(); –