Angular 6拦截器执行数百次

时间:2018-09-05 13:00:52

标签: angular interceptor angular-http-interceptors

在Angular 6应用程序中,我设置了一个拦截器,因为我需要重新路由将要转到另一个域的API调用。

其中一部分是建立新的URI。

这是拦截器代码。

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpClient } 
from "@angular/common/http";
import { Observable } from "rxjs/Rx";


@Injectable()
export class Interceptor implements HttpInterceptor {
    constructor(private http: HttpClient){}
    intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {



    // Clone the request to add the new header.
    const authReq = req.clone({ headers: req.headers.set("headerName", 
   "headerValue")});
    if(authReq.url.search('MS/')!=1){

        var url = 'api/RequestHandler/?uri=' + authReq.urlWithParams;
        this.http.get(url).subscribe(
            success =>{
            console.log("Succefully completed");
            }
        )

        console.log("Sending request with new header now ...");

        //send the newly created request
        return next.handle(authReq)
        .catch((error, caught) => {
        //intercept the respons error and displace it to the console
        console.log("Error Occurred");
        console.log(error);
        //return the error to the method that called it
        return Observable.throw(error);
        }) as any;
      }
    }
}

我看到的是Interceptor代码执行了数百次,并且每次URI串联发生时,我都有成百上千个这样的请求。

http://localhost/mywebapplication/api/RequestHandler/? 
uri=api/RequestHandler/?uri=api/RequestHandler/? 
uri=MS/MappingServicesWebAPIIntegrated/api/myApicontroller? 
Year=2018

在每个后续呼叫中添加一个额外的“? uri = api / RequestHandler /“

只有1个正确的呼叫“ http://localhost/mywebapplication/api/RequestHandler/?     uri = MS / MappingServicesWebAPIIntegrated / api / myApicontroller?     Year = 2018“

如何停止拦截器正在接听的重复呼叫并为其构造错误的url?

0 个答案:

没有答案