JGCW
JGCW

Reputation: 1529

Angular Interceptor calls recursively on page refresh

I am using an angular interceptor to modify all the http request hitting the API end.

When this only happens when I refresh the app from the browser.

this.httpGET('api_handshake').subscribe(response => {
    this.APIHandShakeStatus = true
    if(response['status']==true){
        this._HS_STATUS = true
    } 
}, error => {
    this.logout()
});

which calls the:

httpGET(path: string, getData=null): Observable<any>  {

    const token: string = this.TOKENS.access_token;

    let headers = new HttpHeaders();
    headers  = headers.append('Content-Type', 'application/json');
    headers  = headers.append('Authorization', 'Bearer ' + token);


   let params = new HttpParams();
    params = params.append('uId', this._userDetails['uId']);
    if(getData!=null){
        for (let key in getData) {
            // Begin assigning parameters
            params = params.append(key, getData[key]);
        }
    }


    return  this._http.get(this.API_URL + path, { params, headers})
}

the this._http.get is intercepted using a standard interceptor:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token: string = this.global.TOKENS.access_token;

    //logging the updated Parameters to browser's console
    console.log("Before making api call : ", 'test');
    return next.handle(request).pipe(
        map((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                console.log('event--->>>', event);
                // this.errorDialogService.openDialog(event);
            }
            return event;
        }),
        catchError((error: HttpErrorResponse) => {
            let data = {};
            data = {
                reason: error && error.error.reason ? error.error.reason : '',
                status: error.status
            };

            if(data['status']==401){
                console.log('unauthroized')
                console.log(data)
            }
            return throwError(error);
        }));
}

On a fresh start, I authenticate myself and I login into the app which calls the function below, it works perfectly fine. Then I refresh the app from the browser which calls this function.

On chrome debugger:

httpGET('api_handshake').subscribe

line was getting called repeatedly. If i remove the interceptor, everything works fine.

Upvotes: 0

Views: 1266

Answers (1)

JGCW
JGCW

Reputation: 1529

I was able to figure out the problem. There was a cyclic dependency from the service to the interceptor. However, angular did not throw any cyclic dependency error nor did the debugger loop through the dependencies. Spent more than half a day to figure this out.

When there is a cyclic dependency between an interceptor and a service. It's impossible to debug the error as this is not caught in angular compiler.

Upvotes: 1

Related Questions