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 with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...

A guide on utilizing buttons within ion list items to execute actions independently for both the button and the list item

Currently, I have a list item with a button that is displayed based on a certain condition. My issue is that when I click the button, a popup should appear, but instead, it also navigates to the next page in the background. Can someone help me figure out h ...

The style fails to load correctly upon the page's initial loading

I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d26282823603e212429283f0d7b63756378">[email protected]</a> in a <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026c677a76 ...

Angular: Using ngrx for Nested HTTP Calls

Looking at my Angular code, I am trying to figure out how to convert nested HTTP calls into the ngrx pattern. My idea is to create separate actions for getUser and getPost, but I am struggling with passing the getUser response as a parameter to the getPo ...

Can the type of a prop be specified in the parent component before it is passed down to the children components that utilize the same prop?

In my codebase, I have a component called NotFoundGuard. This component only renders its children if a certain condition is true. Otherwise, it displays a generic fallback component to prevent redundancy in our code. I am trying to figure out if there is ...

Search functionality in Angular using column-based filtering algorithm

Take a look at my table view below. Each column has its own search function. My current issue is that when I type in one column, the same text appears in other columns as well. To solve this problem, I have implemented the following code: <tr& ...

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...

Leveraging uninitialized data in Angular

<ul class="todo-list"> <li *ngFor="let todo of todos" [ngClass]="{completed: todo.isDone, editing: todo.editing}" > <div class="view"> <input class="toggle" type="checkbox" [checked]="tod ...

Encountering a syntax issue with pipeable operators in Angular Rxjs

I am currently in the process of rewriting this code snippet: Observable .merge(this.searchQuery$, this.lazyQuery$) .do(() => this.loadingPage()) .map(filter => this.buildURL("jaume", Config.security['appName'], filter)) .s ...

Adjusting slidesPerView based on screen size in Ionic: A step-by-step guide

Recently, I encountered an interesting challenge while working on my ionic project. I had successfully created a slider using ion-slides to display multiple products. Everything was working perfectly for the portrait view with 1.25 slides per view (slide ...

What is the most effective approach to scan Angular 2, 4, 5 template html files before AOT compilation for optimal code quality assessment?

Recently, I stumbled upon an interesting GitHub repository called "gulp html angular validate". If you're not familiar with it, you can check it out here. However, I have doubts about whether this tool is suitable for Angular 2+ projects. Additionall ...

Changing a date format in typescript: Here is how you can easily convert a date from one

Using React with Typescript: I am currently working with a date picker from material-ui version 5. The date picker requires the date value to be in the format "yyyy-MM-dd". However, the API returns a Date object in the format "2022-01-12T00:00:00.000+00:0 ...

Incorporating Swift code into a NativeScript app

I'm attempting to integrate native Swift code into my NativeScript application. Despite following the guidelines provided in the documentation, specifically adding a Swift source file to App_Resources/iOS/src/ and using publicly exposed classes direct ...

Encountering issues with Angular 12 optimized build, the error messages are sparse and offer little

While my project compiles without any issues in development mode with the build optimizer turned off, I encounter an error during production build: ✔ Browser application bundle generation complete. ✔ ES5 bundle generation complete. ✔ Copying assets c ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

The primary filter for ag-Grid in Angular 2+

When using the default filtering on ag-grid, I find that the timing between typing and filtering is too quick. Is there a method to slow down this process? Perhaps instead of triggering the filter when typing stops, it could be activated by pressing a bu ...

What is the best way to exclude React.js source files from a fresh Nest.js setup?

My setup includes a fresh Nest.js installation and a directory named "client" with a clean create-react-app installation inside. Here is the project structure: ./ ...some Nest.js folders... client <- React.js resides here ...some more Nest.js fo ...

The NgbTooltip does not activate when hovering over a <td> cell

I'm currently facing an issue with implementing ngbTooltip on <table> elements. Initially, I had trouble with <th>, but that was resolved by using the container attribute after referring to this helpful post. The main challenge arises ...

What is the best way to decide on a method's visibility depending on who is calling

I am curious about the best approach for providing methods with "privileged access" that can only be called by specific object types. For instance, if you have a Bank object with a collection of Accounts, you may want to allow the Bank object to call acco ...

What is the best way to make the current tab stand out?

I have implemented a TabHeader component to create a dynamic Tab Menu that displays table contents based on months. The loop runs from the current month back to January, and the content is updated dynamically through an API call triggered by changes in the ...