• AngularJS5.0 (第四篇)--拦截器


    开发过程中,经常有在给后台发请求的时候,设置请求头信息(angular5的拦截器可以很方便实现)

      1,新建services/Interceptor.service.ts

      

    import { Injectable } from '@angular/core';
    import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
    import { catchError } from 'rxjs/operators';
    import { mergeMap } from 'rxjs/operators';
    
    @Injectable()
    export class InterceptorService implements HttpInterceptor {
        constructor( ) {}
    
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            // const authReq = req.clone({
            //     url: (req.url + '&token=ujusaruu19')  // 对任意请求的url添加token参数
            // });
    
            // return next.handle(authReq).pipe(mergeMap((event: any) => {
            //     if (event instanceof HttpResponse && event.status !== 200) {
            //         return ErrorObservable.create(event);
            //     }
            //     return Observable.create(observer => observer.next(event)); // 请求成功返回响应
            // }),
            //     catchError((res: HttpResponse<any>) => { // 请求失败处理
            //         switch (res.status) {
            //             case 401:
            //                 break;
            //             case 200:
            //                 console.log('业务错误');
            //                 break;
            //             case 404:
            //                 break;
            //             case 403:
            //                 console.log('业务错误');
            //                 break;
            //         }
            //         return ErrorObservable.create(event);
            //     }));
            const Auth = `Bearer 3fba7ad7607aac6ca24a5c97dbdc7afce60c80b8`;
            req = req.clone({
                setHeaders: {
                    Authorization: Auth,
                    Accept: 'application/json',
                    ddd: '123'
                }
            });
            return next.handle(req);
        }
    }

    在app.module.ts中注入拦截器:

      import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; /*拦截器和ajax模块*/

      

    providers: [ /*定义的服务 回头放在这个里面*/
      {
        provide: HTTP_INTERCEPTORS,
        useClass: InterceptorService,
        multi: true
      },
      LoginService
    ],
  • 相关阅读:
    【Henu ACM Round#17 A】Simple Game
    【Henu ACM Round #12 E】Thief in a Shop
    【Henu ACM Round#16 D】Bear and Two Paths
    【Henu ACM Round#16 A】 Bear and Game
    P4824 [USACO15FEB]Censoring (Silver) 审查(银)
    P4001 [BJOI2006]狼抓兔子
    P2444 [POI2000]病毒
    P3966 [TJOI2013]单词
    P3796 【模板】AC自动机
    P4574 [CQOI2013]二进制A+B
  • 原文地址:https://www.cnblogs.com/sdorm/p/8805964.html
Copyright © 2020-2023  润新知