Variable value is not visible in intercept method- HTTP Interceptors Angular

788 views Asked by At

I'm trying to pass the variable value in the headers of HTTP request using HTTP Interceptors. But it's not happening

I have tried passing the variable from AppComponent to Service. I can see the variable value but in the same service under Intercept method, I'm not able to

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import * as $ from 'jquery';


@Injectable({
  providedIn:'root'
}) 
export class AppInterceptorService implements HttpInterceptor{

  etag : string
  headers : HttpHeaders

constructor() {}
getEtag(etag : string) {

  if(etag) {
    this.etag = etag;
    console.log("Etag from Interceptor :"+ this.etag)
   }
   else {
     this.etag = '*'
   }

}

handleError(error : HttpErrorResponse) {
    console.log("Error Occured")
    return throwError(error)
}

intercept(req: HttpRequest<any>, next: HttpHandler,): Observable<HttpEvent<any>> {
console.log("interceptetag : " + this.etag)

if(req.method === "GET"){
  this.headers = new HttpHeaders ({
    'Content-Type'    : 'application/json;odata=verbose',
    'Accept'          : 'application/json;odata=verbose',
    'X-RequestDigest' : $("#__REQUESTDIGEST").val(),
    'X-HTTP-Method': 'MERGE',
    'IF-MATCH': "40",

  })
}

if(req.method === "POST"){
  console.log("Etag form POST :"+this.etag)
  this.headers = new HttpHeaders ({
    'Content-Type'    : 'application/json;odata=verbose',
    'Accept'          : 'application/json;odata=verbose',
    'X-RequestDigest' : $("#__REQUESTDIGEST").val(),
    'X-HTTP-Method': 'MERGE',
    'IF-MATCH': this.etag,

  })
}


  const clone = req.clone({'headers' : this.headers})

    return next.handle(clone)
    .pipe(
        retry (1),
        catchError(this.handleError)
    )
}


}

On Button Click: (Component Class)

update() {
    console.log("ETag :" + this.etag)  // "40"
    this.appInterceptorService.getEtag(this.etag) // Here I'm passing "40" ro above service
    this.sharepointService.PostReqNo(this.counter).subscribe()

AppModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule,FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { SharePointService } from './services/sharepointservice.service';
import { AppInterceptorService } from './services/app-interceptor.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    FormsModule,
    HttpClientModule

  ],
  providers: [SharePointService, 
              {'provide' : HTTP_INTERCEPTORS,
               'useClass' : AppInterceptorService,
                'multi' : true}],

  bootstrap: [AppComponent]
})
export class AppModule { }

1

There are 1 answers

3
nash11 On

As per the documentation, intercept has a return type Observable<HttpEvent<any>> and you're not returning anything in your intercept function. There is also a syntax error in your intercept function (You have put a : but not specified a return type) You can either remove the : altogether or specify the return type Observable<HttpEvent<any>> although it would better to specify the return type to keep your code strongly typed.

You can return an empty observable for testing purposes.

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  console.log("interceptetag : " + this.etag) 
  return new Observable<any>();
}

Here is a working example on StackBlitz