Swagger editor is creating a TypeScript client that is unable to successfully make POST requests

After creating an Angular2 typescript client using the Swagger Editor found at http://editor.swagger.io, I encountered an issue where POST endpoints were not functioning properly. Despite setting up all API endpoints successfully, any POST requests failed to reach the server.

The specific method in the generated typescript code appeared correct as the headers were being set accurately. However, upon closer inspection, it seemed that the issue lied within the this.http.request call itself.

public snapshotsFoo (data: Array<number>, extraHttpRequestParams?: any ) : Observable<models.Snapshot> {
    const path = this.basePath + '/Snapshots/foo';

    let queryParameters = new URLSearchParams();
    let headerParams = this.defaultHeaders;
    headerParams.set("Content-Type", "application/json");
    // verify required parameter 'data' is not null or undefined
    if (data === null || data === undefined) {
        throw new Error('Required parameter data was null or undefined when calling snapshotsFoo.');
    }
    let requestOptions: RequestOptionsArgs = {
        method: 'POST',
        headers: headerParams,
        search: queryParameters
    };
    requestOptions.body = JSON.stringify(data);

    console.log('I am in foo', path, requestOptions);

    return this.http.request(path, requestOptions)
        .map((response: Response) => {
            if (response.status === 204) {
                return undefined;
            } else {
                return response.json();
            }
        });
}

Interestingly, while the endpoint worked seamlessly on the swagger ui (), POSTman, and even via cURL commands, the same functionality seemed to be missing when using the generated typescript code. No errors were thrown, yet nothing was posted to the server.

Answer №1

It seems like the http observable was being removed by garbage collection before it could be posted (based on my observations).

Here is how the issue appeared in my component:

...
this.snapshotApi.snapshotsFoo([6,7,8]);
...

And here is how I resolved the problem in my component:

...
let whocares = this.snapshotApi.snapshotsFoo([6,7,8]);

whocares.subscribe(res => {
    console.log('I'm not even sure');
}

Any insights or comments on what exactly is happening would be appreciated. Posting to the server is now functioning correctly. It appears that observation is altering behavior...

Answer №2

I encountered a similar issue when I realized that I had forgotten to subscribe to my API call. After referring to the Rx documentation, I learned that:

An Observable is considered a "cold" Observable if it does not start emitting items until an observer subscribes to it. On the other hand, an Observable is classified as a "hot" Observable if it can emit items at any time, and a subscriber may start observing the emitted items after its commencement, potentially missing items emitted prior to the subscription.

For instance, in this scenario, the HttpClient returns a cold observable that allows us to perform additional actions on the sequence, triggering only when it is subscribed to.

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

The ngFor directive in Angular2 consistently collapses the identical <tr> element

Greetings, I am a newcomer to the world of web development. Recently, I used the *ngFor directive in Angular to generate multiple rows with collapsible details. However, when I click on a row, it always collapses the same div, instead of the corresponding ...

Issue: Unforeseen reserved term

I encountered an issue while running a simple test case where I received an error message stating "unexpected reserved keyword." The error is pointing to the import keyword in the line import * as chai from 'chai'. Below is my test code: "use st ...

Issues encountered when attempting to use Angular2 with SystemJs and typescript transpiler

I've encountered an issue with my TypeScript transpiler setup. My @angular component isn't loading, and I'm getting this error message: ZoneAwareError: "Error: core_1.Component is not a function Evaluating http://127.0.0.1:64223/app/app.c ...

Understanding the values of attributes when submitting a reactive form

My form is built using Angular's reactive forms and includes an input element with custom attributes: <input type="text" [attr.data-challengeId]="value.id" [formControlName]="value.label"> When I submit the form, I only receive the value of th ...

Tips for maintaining license comments in TypeScript 2.5

When creating JavaScript libraries using TypeScript v2.5 and tsc, it is important to include license comments in the built files. However, the removeComments configuration in the tsconfig.json file can remove certain comments, including license comments. ...

Retrieve route parameters in Angular 6 without using promises

I am currently utilizing Angular 6. When working with route parameters, I typically use the following code snippet: this.route.params.subscribe(params => { // params can now be utilized as an object variable }); However, I find myself needing to a ...

Encountered an error with ng build --prod while attempting to import a JavaScript file within the app module

Is it possible to import a javascript file into my app module without access to the ts file? import { OtherComponent } from './node_modules/blahblah/OtherComponent.js' While trying to declare this component in @NgModule and running "ng build -- ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

express-typescript-react: The frontend bundle file could not be located (404 error)

Currently, I am in the process of developing a full stack application that utilizes Express (written in Typescript) and React. One key component of my development setup is webpack, which I'm using to bundle both the backend and frontend parts of the a ...

Transforming Java Web Project into Angular using Java

I'm currently working on a Java web project that uses JSP for the frontend and Java for the backend. I'm looking to convert this project to have an Angular frontend and keep the Java backend. Despite my efforts in searching online, I haven't ...

Excessive notification events are currently causing a blockage in the Angular app

Currently, I am utilizing Angular 7 in combination with SignalR on the backend for push notifications. At certain times, an overwhelming amount of notifications flood in, causing my application to become completely unresponsive. The SignalR service compon ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Number input field failing to update value upon pressing 'enter'

App features an input element that updates when the user presses enter, clicks away, or clicks the next button. Upon inspecting the element in the developer tools, it was observed that the value attribute updates when the user clicks away or clicks the nex ...

Learn the steps for applying unique CSS styles to your ngx-bootstrap modal by utilizing modalService. Discover the benefits below

I am facing a unique challenge in my project. I have to incorporate a modal animation similar to the one showcased in this example. However, I also need to include a custom component (our filter component for a data table) within the modal. To achieve this ...

What is the maximum UIRouter version that is supported with Angular 6?

Scenario: As my team and I near the completion of migrating our app from AngularJS to Angular 6, we are facing a dilemma. We are currently using UIRouter's implementation for angular-hybrid, and we are not ready to switch to Angular routing just yet. ...

I'm curious about how to link a JSON field using dot notation in Angular 12 HTML

Does anyone know how to bind a JSON field using dot paths in Angular 12 HTML? For example: //Angular data: any = { name: 'x1', address: { city: 'xyz' } }; field: any = 'address.city'; //Html <input [(ngModel)]="data[ ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...

Tips for Implementing Error Handling in Angular using Sweetalert2

On this code snippet, I have implemented a delete confirmation popup and now I am looking to incorporate error handling in case the data is not deleted successfully. confirmPopUp(){ Swal.fire({ title: 'Are You Sure?', text: 'Deleti ...

Transferring a document through an Angular form group and sending it to a Django API

I'm facing an issue with a form in Angular that contains multiple entries such as name, email, phone number, and a file field. I have grouped all these elements using a Form group. The corresponding model is in Django (utilizing Django Rest Framework) ...

The Bootstrap Grid seems to be failing to recognize breakpoints after being imported into a Component SCSS file

After importing Bootstrap Grid into an Angular Component SCSS file, the Grid Column Breakpoints in the HTML file become broken or ignored. app.component.scss @import '../../node_modules/bootstrap/scss/bootstrap-grid'; // Some styles with media ...