Search code examples
angularinterceptorangular-http-interceptors

How submit Angular form with Http Interceptor


Do you know how can I submit my form using HttpInterceptor? My GET method it is ok using interceptor getting token and bringing the result etc... but when I try to submit my form nothing happen, the back-end is not being called.

TokenInterceptor.ts

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(private kcService: KeycloakService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
    return from(this.kcService.init())
      .pipe(switchMap(authToken => {
        debugger;
        if(authToken){
          const headers = request.headers
            .set('Authorization', 'Bearer ' + authToken)
            .append('Content-Type', 'application/json');
          console.log(authToken);
          const reqClone = request.clone({
            headers
          });
          return next.handle(reqClone);
        }
      }));
  }

}

ItemService.ts

@Injectable()
export class ItemService {

    itensUrl = 'http://localhost:8080/itens'

    constructor(private http: HttpClient, private kcService: KeycloakService) { }

    list(){
     return this.http.get<any[]>(this.itensUrl);
    }

    addiction(item: any){
      return this.http.post(this.itensUrl, item);
    }
  }

app.modules.ts:

 providers: [
    ItemService,
    KeycloakService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }

ItemPatrimonyComponent.ts

export class ItemPatrimonyComponent implements OnInit {

  itens = [];

  constructor(private itemService: ItemService) { }

  ngOnInit() {
    this.listAll();
  }

  listAll(){
    this.itemService.list().subscribe(data => this.itens = data)
    console.log(this.itens);
  }

  add(frm:FormControl){
    this.itemService.addiction(frm.value)
      .subscribe(() => {
        frm.reset();
        this.listAll();
       });
  }

Solution

  • The problem is on Keycloak init function, and you could not debug your problem because on your interceptor you are adding the debugger inside the callback of init instead of outside it. If init is called and refresh the page (what keycloak does) you will never see the callback debugger working, what you need to do is on your keycloak service instead of call directly init verify if the token is already defined if it returns the token instead of call keycloak.init on each request. Something like:

    if (this.keycloak.token) {
      return Promise.resolve(this.keycloak.token);
    }
    return this.keycloak.init().then(()=> this.keycloak.token)