Having trouble retrieving return values from the http post method in Angular4

I need to send a http post request to a Web API in order to save user-entered data. The Web API will return some values, such as the TransactionId, which will be used for further logic in other functions. I'm new to Angular and although I've seen similar questions, I'm still struggling with it. It's a challenging task for me, so any help would be greatly appreciated.

Here is the Http post method call:

    CatchHeaderDetail(stock: any)
    : Observable<IHeaderstock[]> {
    let stockheaderdetail = stock;
    console.log(stockheaderdetail)
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this._http.post('http://localhost:3041/api/Stockcountheader/' + 'Stock', stockheaderdetail, options)
        .map((response: Response) => <IHeaderstock[]>response.json())
        .catch(this.handleError);

}

The Angular4 component invokes this service to save the data:

Onclick(){

        this.header = new IHeaderstock(this.userid, this.created, this.CompanyID, this.modified, this.modifieduserid, this.confirm, this.shopid);
    this.headeritems.push(this.header);


    this._enqService.CatchHeaderDetail(this.headeritems)
        .subscribe(value => {
            if (typeof value !== 'undefined' && value != null) {
                value.forEach(header => {
                    this.headeritems.push(this.header)
                });

            }
        },

            error => {
                console.error(error);
                this.statusMessage = "Problem with the service.Please try again after sometime";
            });

This is how MY API looks like:

        [HttpPost]
    public IHttpActionResult Stock([FromBody] List<spGetNewStockCountHeader_Result> jsonvalues)
    {

        ObjectParameter TransactionId = new ObjectParameter("TransactionId", typeof(Int32));
        foreach (spGetNewStockCountHeader_Result Datastock in jsonvalues)
        {

            spGetNewStockCountHeader_Result Stockobject = new
            spGetNewStockCountHeader_Result();
            Stockobject.UserID = Datastock.UserID;
            Stockobject.created = Datastock.created;
            Stockobject.CompanyID = Datastock.CompanyID;
            Stockobject.modified = Datastock.modified;
            Stockobject.modifieduserid = Datastock.modifieduserid;
            Stockobject.confirm = Datastock.confirm;
            Stockobject.ShopId = Datastock.ShopId;

            enqentities.spGetNewStockCountHeader(Datastock.UserID,  Datastock.created, Datastock.CompanyID, Datastock.modified,
                Datastock.modifieduserid, Datastock.confirm,
            Datastock.ShopId, TransactionId).First();

        }

        return Ok(new { data = TransactionId.Value }); // i want this value to get in the angular4
    }

Answer №1

Modify the code below: ensure that the map operator correctly maps the data. Note that the actual data is not an array, but rather a single value.

CatchHeaderDetail(stock: any): Observable<any> {
        let stockheaderdetail = stock;
        console.log(stockheaderdetail);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.post('http://localhost:3041/api/Stockcountheader/' + 'Stock', stockheaderdetail, options)
            .map((response: Response) => {
            return response.data;
            })
            .catch(this.handleError);

    }


Onclick(){
        this.header = new IHeaderstock(this.userid, this.created, this.CompanyID, this.modified, this.modifieduserid, this.confirm, this.shopid);
    this.headeritems.push(this.header);


    this._enqService.CatchHeaderDetail(this.headeritems)
        .subscribe(value => {
        if (value) {
            //use the value for further processing. Remember that the value is an integer, not an array.
        }
    },error => {
                console.error(error);
                this.statusMessage = "There was a problem with the service. Please try again later.";
            });

}

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

Attempting to implement dynamic selectors in my functions to avoid redundancy

Here is some code I find myself writing frequently for parsing JSON or creating functions. // Reusable adder functions async function addImagesToEntity(entityId, fileName, entity) { const entity = await db.${entity}.findById(entityId); await entity.${e ...

What is the reason behind `ngAfterViewChecked` and `ngAfterContentChecked` being invoked twice?

import { AfterContentChecked, AfterViewChecked, Component } from '@angular/core'; @Component({ selector: 'app-root', template: '' }) export class AppComponent implements AfterViewChecked, AfterContentChecked { ngA ...

Encountering a 'Duplicate identifier' issue while trying to transition project to Typescript

Currently in the process of transitioning an existing JavaScript application to TypeScript. To facilitate a gradual conversion, I began by utilizing the "allowJs" compiler option to compile the original JavaScript code. However, as I start converting files ...

Tips for updating an array in TypeScript with React:

Encountering an issue while updating my state on form submission in TypeScript. I am a newcomer to TS and struggling to resolve the error. enum ServiceTypeEnum { Replace = 'replace product', Fix = 'fix product', } interface IProduc ...

Resizing the md-dialog-container in angular-material2 can be achieved by adjusting the size based on the dropdown component present in the

Currently, I am utilizing Angular Material2's dialog component. Within the dialog, I have incorporated input fields and angular2-dropdown-multiselect. The issue arises when I open the dropdown, as it automatically adds a scrollbar to the dialog box. ...

Unleashing the full potential of Angular 7: How a personalized class decorator can

My dilemma lies in the fact that I have a decorator which, when applied on ngOnInit, initiates a console.log. log.decorator.ts export function Log(): ClassDecorator { // The Decorator Factory return (target: Function) => { const ngOn ...

Only apply patches to untouched values

Looking for a way to patch only the pristine properties of my reactive form in Angular. Received updates from a websocket service regarding user data, and want to update the form based on the payload without changing dirty properties. Below is the code s ...

The issue lies in attempting to assign an 'Observable<number[]>' to a parameter expecting an 'Observable<ProjectObject[]>'. This obstacle must be overcome in order to successfully create a mock service

I am currently working on setting up a mock service for unit testing, but I am facing an issue where the observable is not returning the expected fake value. Can someone please assist me in resolving this problem and also explain what might be wrong with m ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...

Transforming a map into a plain object for TypeScript declaration

Here is a scenario: let cachedPromises: Map<string, Promise<any>> = new Map(); Can you provide the equivalent declaration for a plain object? Perhaps something along these lines: interface IMyMap { [key: string]: Promise<any> } let ...

Determining the position of the selected option in an Angular 2 Select menu

Is there a way to retrieve the position of the selected option in a similar manner to the index of a table? Example for a table: <tr *ngFor="let car of cars; let i = index" (click)="showTabs(i)"> <td>{{i+1}}</td> </tr> I am lo ...

Chakra UI Icons in Next.js App Triggering Unsupportive "export *" Bug

Description: Currently, I am developing a Next.js application and incorporating the Chakra UI library for styling and components. However, I have run into an obstacle with the Chakra UI icons package during the build process. Error Message: ./node_module ...

Using default parameters in a versatile function

There is a function called zip with the following signature: function zip<T, U, V>(ts: T[], us: U[], zipper: (t: T, u: U) => V): V[] An attempt is made to assign a default value of (t, u) => [t, u] to the zipper argument: function zip<T, ...

The Bootstrap modal backdrop is now displaying prominently in front of the modal following the latest Chrome update

Chrome version: Version 111.0.5563.64 (Official Build) (x86_64) Bootstrap: 4.3.1 Recently, there has been an issue with the modal backdrop appearing in front of the modal itself after a Chrome update. The problem does not seem to be related to z-index, an ...

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...

What are some methods to avoid redundant data across various windows?

In the process of developing an angular application, I have implemented a websocket for real-time updates transmission and reception. Within my application, users have the ability to open multiple windows that are launched from the main window, solely for ...

Issue: Dynamic invocation of click events on anchor tags is not working in Angular

Having a challenge with Angular(2+). I've created a menu with anchor tags. We can manually select a menu item or use the keyboard to press Enter to select it. <a (click) = 'selectItem(item)' id='menuItem1'>Menu item</a> ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

Positioning 3D objects in Three.js

I am working on a 3D Scene using Three.js with an Earth shape that currently looks like this: https://i.sstatic.net/zXWki.png My goal is to modify it to resemble something like this: https://i.sstatic.net/w4ypV.jpg The coloring, stars, and texture are ...

Guide on switching locales from US to Japan in react-big-calendar

Currently, I am trying to customize a calendar component using the react-big-calendar library. My goal is to localize it for Japan, but I'm facing some challenges. Error Message: Unexpected require(). 'ja' is defined but never used. Code S ...