There is an issue with the Angular Delete request functionality, however, Postman appears to be

HttpService

 delete<T>(url: string): Observable<T> {
    return this.httpClient.delete<T>(`${url}`);
  }

SettingsService

deleteTeamMember(companyId: number, userId: number): Observable<void> {
    return this.httpService.delete<void>(
      `${environment.urls.api}/company/${companyId}/team/${userId}`
    );
  }

component.ts

 this.settingsService
          .deleteTeamMember(this.company.companyId, teamMember.userId)
          .subscribe(); //api call

The API request above is encountering a 400 Bad Request error. It includes access tokens and other necessary credentials.

API response

{
    "code": "BadRequest",
    "title": "Bad Request",
    "message": "Expected one of: <<{,[>> but got: <<EOF>>",
    "type": "tag:oracle.com,2020:error/BadRequest",
    "instance": "tag:oracle.com,2020:ecid/XgKKiZB497hJdOcC1jQxOQ"
}

Strangely, the same API request and access token function properly in Postman. Any insights on why?

AuthInterceptor

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private isRefreshing = false;

  private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
    null
  );

  constructor(
    private authService: AuthService,
    private userDataService: UserDataService
  ) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    let authRequest = request;
    const accessToken = this.userDataService.getAccessToken();

    if (accessToken != null) {
      authRequest = this.addTokenHeader(request, accessToken);
    }

    return next.handle(authRequest).pipe(
      catchError((error) => {
        if (
          error instanceof HttpErrorResponse &&
          !authRequest.url.includes('auth/sign-in') &&
          error.status === 401
        ) {
          return this.handle401Error(authRequest, next);
        }

        return throwError(error);
      })
    );
  }

  private handle401Error(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);

      const refreshToken = this.userDataService.getRefreshToken();

      if (refreshToken) {
        return this.authService.refreshToken(refreshToken).pipe(
          switchMap((token: TokenModel) => {
            this.isRefreshing = false;

            this.userDataService.setAccessToken(token?.accessToken);
            this.userDataService.setRefreshToken(token?.refreshToken);

            this.refreshTokenSubject.next(token.accessToken); //get the 'accessToken' from refreshToken() call

            return next.handle(this.addTokenHeader(request, token.accessToken));
          }),
          catchError((err) => {
            this.isRefreshing = false;

            this.userDataService.setIsSignedOut(true); //Sign Out the app

            return throwError(err);
          })
        );
      }
    }

    return this.refreshTokenSubject.pipe(
      filter((accessToken) => accessToken !== null),
      take(1),
      switchMap((accessToken) =>
        next.handle(this.addTokenHeader(request, accessToken))
      )
    );
  }

  private addTokenHeader(
    request: HttpRequest<any>,
    accessToken: string
  ): HttpRequest<any> {
    return request.clone({
      setHeaders: {
        'Content-Type': 'application/json',
        'Access-Token': accessToken,
      },
    });
  }
}

Answer №1

To streamline your interceptor, consider eliminating the

'Content-Type': 'application/json'
line. Angular automatically includes this header when necessary, so it's not required for delete requests.

private updateTokenHeader(
    req: HttpRequest<any>,
    token: string
  ): HttpRequest<any> {
    return req.clone({
      setHeaders: {
        'Content-Type': 'application/json', // DELETE THIS LINE
        'Authorization': `Bearer ${token}`,
      },
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

Having difficulty accessing certain code in TypeScript TS

Struggling with a TypeScript if else code that is causing errors when trying to access it. The specific error message being displayed is: "Cannot read properties of undefined (reading 'setNewsProvider')" Code Snippet if (this.newsShow != ...

What is the best way to retrieve an ng-model parameter within a controller?

I'm working on implementing a PUT method in my controller and need to bind the new value back to it. I've tried: <div ng-app="myApp" ng-controller="personCtrl"> <form> First Name: <input type="text" ng-mod ...

Developing an Angular application and hosting it on an Apache server without the need

I am facing an issue where I need to share an Angular application with an external team, but they are encountering a 404 Not Found error when trying to load a page directly. Unfortunately, I do not have access to the Apache server where the application is ...

Update the data in a table using Angular

I am currently displaying an array in a table, but I need to make edits to all the values in one specific column of the table. Here is an excerpt from my code: <tr *ngFor="let line of invoice.lines; let index = index"> <td> {{line. ...

Can metadata be attached to data models in Angular for annotation purposes?

Looking to add some metadata annotations to a simple data model export class Certification { title: string; certificationType?: CertificationType; validTo?: number; description?: string; externalIdentifier: Guid; constructor() { ...

Using type as an argument in a hook in a similar fashion to how it is

My custom hook utilizes Zustand and is capable of storing various data types. However, I am looking to specify the type of data that will be stored similar to how it is done with the useState hook. import { Profile } from "@/types"; import { crea ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Choosing to overload the plainToClass function may result in a type error

I've been tasked with compiling an angular project that contains mostly code written by someone else. Although the example below compiles successfully on one machine, it throws an error on different machines. import { plainToClass } from 'class ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

The AnimationRendererFactory ahead-of-time (AOT) compilation is encountering an issue where it is unable to access the property 'create

I am encountering an issue while trying to compile my Angular4 app AOT. The error message that I am stuck on is: TypeError: Cannot read property 'createRenderer' of undefined at AnimationRendererFactory.createRenderer (http://localhost:8080/cwp/ ...

Integrating TypeScript into an established project utilizing React, Webpack, and Babel

Currently, I am in the process of integrating Typescript into my existing React, Webpack, and Babel project. I aim to include support for file extensions such as [.js, .ts, .tsx] as part of my gradual transition to Typescript. I have made some progress, b ...

Modify animation trigger when mouse hovers over

I am looking to create a feature where a slide overlay appears from the bottom of a thumbnail when the user hovers over it, and retracts when the user is not hovering. animations: [ trigger('overlaySlide', [ state(&ap ...

Is there a way to set the submitted variable to true when the form group is submitted, then revert it to false when the user makes changes to the form?

With just one FormGroup, I ensure that when a user submits the form with errors the 'submitted' variable is set to true, displaying the errors. However, my challenge now is how to reset this variable to false when the user makes any changes after ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...

Angular 5 dynamically updates its model after the completion of events

The issue at hand Currently, I am working with angular 5 and have created a component that consists of 3 controls. <ss-multiselect-dropdown id="type" formControlName="type" (ngModelChange)="onChange('type')"></ss-multiselect-dropdown&g ...

Is it beneficial to consolidate masterdata calls into a single call?

Our application is built using REST with an Angular 2 client. We frequently make calls to master data APIs such as country and agreement during login, totaling around 6-7 calls. From a performance standpoint, would it be beneficial to consolidate these c ...

Utilizing JSDoc for establishing an index signature on a class in ES6

When working with JSDoc, achieving the equivalent of Typescript's computed property names can be a challenge. In Typescript, you'd simply define it like this: class Test { [key: string]: whatever } This syntax allows you to access these comput ...

I am experiencing issues with staying logged in while using Passport and sessions. The function "isAuthenticated()" from Passport continuously returns false, causing me to not remain logged in

I have been working on implementing authentication with Angular, Passport, and sessions. I can successfully create a new user and log in, but I am facing an issue: Problem Every time I check if the user is authenticated using Passport's isAuthentica ...

Tips for enabling the TypeScript compiler to locate bokeh's "*.d.ts" files

I recently made the switch from Bokeh's convenient inline extension framework to their npm based out of line build system. I'm currently working on getting my extension to build, but I've noticed that Bokeh organizes all TypeScript *.ts.d fi ...