Home > Software design >  Post request doesn't work in Interceptor. Angular 15
Post request doesn't work in Interceptor. Angular 15

Time:12-05

I have a class with get and post requests, also I made an interceptor. Get requsts works, but post not, what's the reason?

Class with request methods:

import { Injectable } from '@angular/core';
import {Observable} from "rxjs";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import { Probe } from '../entities/Probe';
import { TokenStorageService } from '../auth/token-storage.service';
import { JwtResponse } from '../auth/jwt-response';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  private tableUrl = 'http://localhost:8088/api/table';
  private editUrl = 'http://localhost:8088/api/table/edit/';
  private addUrl = 'http://localhost:8088/api/table/add';

  constructor(private http: HttpClient,private token: TokenStorageService) { }

  getProbesBoard() {
    console.log("------")
    return this.http.get<Probe[]>(this.tableUrl);
  }

  getAddBoard() {
    return this.http.get<any[]>(this.addUrl);
  }

  getGetBoard(id:number){
    return this.http.get<any[]>(this.editUrl id);
  }

  putEditBoard(probe:any, id:number){
    console.log('Post')
    this.http.post(this.editUrl id,probe)
  }

  putAddBoard(probe: Probe){
    return this.http.post(this.addUrl,probe);
  }
}

Class interceptor:

import {Injectable} from "@angular/core";
import {HTTP_INTERCEPTORS, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders} from "@angular/common/http";
import {TokenStorageService} from "./token-storage.service";

const TOKEN_HEADER_KEY = 'Authorization';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private token: TokenStorageService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    let authReq = req;
    const token = 'Bearer '   this.token.getToken();
    authReq = req.clone({headers: req.headers.set(TOKEN_HEADER_KEY, token).set('Content-Type', 'application/json')});
    console.log('Intercepted HTTP call', authReq);
    return next.handle(authReq);
  }
}

export const httpInterceptorProviders = [
  {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}
];

Here is the logs: Before a post request Before sending a post request

After a post request After

In the logs it didn't even tried to send a post request

I checked, is the method putEditBoard() is called putting a console.log inside it and it's called after pushing the button

I want to make post requests, which would be refactored by Interceptore

CodePudding user response:

@Barkha was right, subscribe is necessary to put

  • Related