Angular2中拦截器Intercept探究之路

初志

之前看到angular2正式宣布了,过去看了下,觉得不错,因而入坑。
使用过程中想写一个像angular1那样的阻拦器,一同曲折啊

Angular1中的阻拦器

.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);
        }
    };
}])

Angular2中没有供应,须要本身完成

去Stackoverflow上搜了良久,有相关内容是不错,但过期了。不过思绪照样能够自创的。

尝试以下
第一篇链接
第二篇链接
第三篇

@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里写法过期了

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

根据上述代码,写法与angular2 r6差别,不知道怎样改。继续搜刮,发明大部分写法都相同,只是注入体式格局差别,背面看到了r6的注入体式格局,折腾频频,有了效果

本身的Intercept

customhttp.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';
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.ts

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.ts

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
然则不知道怎样壅塞实行,迎接交换

    原文作者:紫气东来_姜波
    原文地址: https://segmentfault.com/a/1190000007153089
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞