1

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 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

3 Comments

I forgot to mention that in the post. I have used return type
Did this fix your problem? If not, what other problem are you facing? Check the working Stackblitz above to see if you missed out anything.
Thanks Nash ! I saw your code & it's the same I have used in my app. Couldn't understand why this isn't working ! It' showing undefined in the intercept method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.