ionic3+ angular4.0.x 开发云小客 会员端之 http 接口监控,实现token管理登录。
功能, 自动在http请求时添加token, 若token过期或者没有附带token, 根据后台返回状态401,500,直接跳转到登录界面。
import { Events, NavController, NavParams ,App } from 'ionic-angular'; import { Injectable, Injector } from '@angular/core'; import 'rxjs'; import {Http, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend, Headers} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {Storage} from '@ionic/storage'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/map'; import { Login } from '../../pages/login/login'; @Injectable() export class HttpInterceptor extends Http { private navCtrl: NavController; constructor(connectionBackend: ConnectionBackend, requestOptions: RequestOptions, app: App, public storage: Storage) { super(connectionBackend, requestOptions); this.navCtrl = app.getActiveNav(); } public get(url: string, options?: RequestOptionsArgs): Observable<Response> { return Observable.fromPromise( this.getRequestOptionArgs(options) ).mergeMap((options) => { return super.get(url, options) }); } private goTo(url: string) { console.info('url: '+ url); // setTimeout(() => this.router.navigateByUrl(url)); } public post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> { return Observable.fromPromise( this.getRequestOptionArgs(options) ).mergeMap((options) => { return super.post(url, body, options) .toPromise() .then(res => this.handleSuccess(res)) .catch(res => this.handleError(res)) }) } public handleSuccess(res: Response) { return res; } public handleError(res: Response) { console.info(res); if (res.status == 401) { console.info(res); } switch (res.status) { case 200: break; case 401: // 未登录状态码 this.navCtrl.setRoot(Login); break; case 403: case 404: case 500: this.navCtrl.setRoot(Login); break; } return res; } public put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> { return Observable.fromPromise( this.getRequestOptionArgs(options) ).mergeMap((options) => { return super.put(url, body, options) }) } public delete(url: string, options?: RequestOptionsArgs): Observable<Response> { return Observable.fromPromise( this.getRequestOptionArgs(options) ).mergeMap((options) => { return super.delete(url, options) }); } private getRequestOptionArgs(options?: RequestOptionsArgs) { return this.storage.get('token').then((token) => { if (options == null) { options = new RequestOptions(); } if (options.headers == null) { options.headers = new Headers(); } // options.headers.append('Content-Type', 'application/json'); if (options.headers.get("token") == null) { // options.headers.append('token','4CA05F76D6954EE39C45D2BD872542665A08252C0DD2953B279DD45C75664449BCAA5B062FF9B4C8D8747A112EC455306EFC21085AED34E4675C4E0D996EF6105DFA912601EFE111'); if (token !== null) { options.headers.append('token', token); } } return options; }); } }