angular 4 httpclient 차단기

1.서비스 생 성:
InterceptorService.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{

  intercept(req:HttpRequest,next:HttpHandler):Observable>{
    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) => {   //      
        switch (res.status) {
          case 401:
            break;
          case 200:
            console.log('    ');
            break;
          case 404:
            break;
          case 403:
            console.log('    ');
            break;
        }
        return ErrorObservable.create(event);
      }));
  }
}

2.공급 자 에 app.module.ts 가 져 오기
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import {InterceptorService} from "./interceptor.service";
import {HTTP_INTERCEPTORS, HttpClientModule} from "@angular/common/http";
import { TestComponent } from './test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {provide:HTTP_INTERCEPTORS,useClass:InterceptorService,multi:true}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3.끝,구성 요소 에서 http Client 요청 을 사용 하면 자동 으로 차단 되 며,차단 처 리 는 Interceptor Service.ts 에서 작 동 합 니 다.
다음으로 전송:https://www.cnblogs.com/changyaoself/p/8539048.html

좋은 웹페이지 즐겨찾기