在Angular中将HttpInterceptor注入app.module.ts问题

时间:2018-10-18 14:18:44

标签: angular typescript

我在Angular 6中有一个拦截器。而且,我想注入我的app.module.ts。因此,我将“ {提供:LocationStrategy,useClass:HashLocationStrategy}” 部分更改为“ {提供:HTTP_INTERCEPTORS,useClass:LoaderInterceptor,multi:true}” 。但是,当我更改或删除LocationStrategy时,我看到空白页,并且控制台中没有错误。这种情况可能是什么原因?

app.module.ts的提供者部分

  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: LoaderInterceptor, multi: true },
    //{ provide: LocationStrategy, useClass: HashLocationStrategy },
    AuthGuard, GlobalVariables, FormBuilder
  ]

loader-interceptor.ts

import { Injectable } from "@angular/core";
import { tap } from "rxjs/operators";
import {
  HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpResponse,HttpErrorResponse } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
  constructor() { }
  //function which will be called for all http calls
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    //how to update the request Parameters
    const updatedRequest = request.clone({
      headers: request.headers.set("Authorization", "Some-dummyCode")
    });
    //logging the updated Parameters to browser's console
    console.log("Before making api call : ", updatedRequest);
    return next.handle(request).pipe(
      tap(
        event => {
          //logging the http response to browser's console in case of a success
          if (event instanceof HttpResponse) {
            console.log("api call success :", event);
          }
        },
        error => {
          //logging the http response to browser's console in case of a failuer
          if (event instanceof HttpResponse) {
            console.log("api call error :", event);
          }
        }
      )
    );
  }
}

0 个答案:

没有答案