"Fetching and Utilizing the Output Parameter from an API in Angular4: A Step-by-Step Guide

Working on a post method in an Angular 4 web app, I am able to save data to the database successfully. However, I am facing an issue where an ID (return value) is passed from the DB to the API for Angular as another function parameter. How can I retrieve that value in my Angular code and use it as the next function parameter? I am new to Angular, so please excuse any mistakes in my question. (I need to extract the TransactionId value from the API to Angular)

Below is my TypeScript (TS file):

 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 some time";
            });
additem{
   this.items = new IStockitems(this.shopid,value.ItemCode, value.ItemDescription, value.PackingtypeName, value.Stock, this.TransactionId );
 }   //here this.TransactionId is the returned value from the above post method.

Next is my service file:

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

}

Lastly, my WebAPI implementation (please note that the API returns the value successfully):

My API implementation (working fine)


 public class StockcountheaderController : ApiController
    {
        private adminv2Entities enqentities = new adminv2Entities();
       [HttpPost]
        private  IActionResult 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);
  }
return Ok(new { data = TransactionId.Value});    
}

Answer №1

Within the API code, you are currently returning what appears to be a JSON object that contains an integer value. However, in the service, you have specified that the response should be an array of values of type IHeaderStock.

To address this issue, you have the option to make adjustments on either side. One solution is to eliminate the IHeaderStock<> type from the service, as shown below:

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

}

Answer №2

The issue lies in your API method where you are returning

return "Ok(new { data = TransactionId.Value});"
, while in your service method or function, you are returning

IHeaderstock ARRAY 
.map((response: Response) => <IHeaderstock[]>response.json()),
You need to ensure that your service in Angular returns either an integer type or updates the transaction value to an IHeaderstock array.

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

Typescript interface created specifically for React Higher Order Component Props

Consider the React HOC provided below which adds sorting state to a component: import React, {Component, ComponentClass, ComponentType} from 'react' interface WithSortState { sortOrder: string } interface WithSortInjectedProps { sortO ...

Adjusting the IntelliSense Functionality in Monaco Editor

Currently, I am testing out the CompletionItemProvider feature for my project. I have implemented two separate CompletionItemProviders. One is set to trigger when any alphabet letter is typed and the other triggers when the user enters a single quote chara ...

Testing an angular function that requires multiple arguments in its constructor

My goal is to conduct unit tests on functions within a component. The constructor for this component requires four arguments. Initially, I attempted to simply set the arguments as (new AClass, new BClass, new CClass, new DClass); however, some of these cla ...

Utilizing Components for Efficient Development in Angular

I have three different types of objects: A - FirstName - LastName B - FirstName - LastName - MiddleName C - FirstName My goal is to create a component that can be used to easily create these objects using a simple form where I can input the necessa ...

What is the best way to utilize the fresh Sanitizer API in Typescript?

Everything seems to be working well on Codepen, even without using window. It's surprising because I'm used to having to use window.x if ( 'Sanitizer' in window ) { console.log( 'sani', 'Sanitizer' in window ); } ...

Angular 2: Despite changes in property, ElementRef.nativeElement.offSetwidth consistently returns the same value

Recently, I encountered an HTML element that caught my attention: <h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1> This particular element piqued my curiosity because the variable "mysize" controls the ...

Encountered an error: Object(...) function not defined when using React, Formik, and Webpack

I have encountered an issue while trying to use both Formik and React-Form-Hooks in my project. Despite using Typescript as my language and Babel as the transpiler, both libraries throw the same error when compiled. Uncaught TypeError: Object(...) is not ...

Typescript fails to identify the parameter type of callbacks

I am facing a challenge with the function below and its callback type: type Callbacks = { onSuccess: (a: string) => void; }; function myFunction(event: string, ...args: [...any, Callbacks]) { } The function works correctly except for one issue - ...

Angular 2 Release Candidate 6 form input pattern always fails to pass

How can I ensure that a required input in my form fails validation if there is no non-whitespace character present? Despite setting the pattern to [/S]+, the validation does not pass. Could I be missing an import or something else? My Template: <form ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

Leveraging Interface in Protractor Testing

As a newcomer to Typescript and Protractor, I have been working with reusable code in various classes. Instead of importing each library class separately into my test class, I am trying to find a way to import just one class or interface that will contai ...

What's the best way to import a file from OneDrive to an Angular app using Typescript?

I am currently working on an Angular application that utilizes OneDrive/Sharepoint for file storage. Authentication is functioning properly, and I can successfully save files. However, I am encountering an issue when attempting to download a file created a ...

Using NodeJS API gateway to transfer image files to S3 storage

I have been attempting to upload an image file to S3 through API Gateway. The process involves a POST method where the body accepts the image file using form-data. I crafted the lambda function in TypeScript utilizing the lambda-multipart-parser. While it ...

Customize buttons in Material UI using the styled component API provided by MUI

I am intrigued by the Material UI Styled Component API, not to be confused with the styled-component library. However, I am facing difficulty in converting my simple button component into a linked button. Can anyone advise me on how to incorporate a react ...

Nested forwardRef in React is a powerful feature that allows

Within my React application, specifically utilizing typescript, I have implemented a form using react-hook-form to handle all the necessary logic. Afterwards, I proceeded to customize the select element with various CSS and additional features. To simplif ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...

Deploying a Meteor and Angular2 application to Heroku

Currently working on an app using Meteor, Angular2 with the angular-meteor package, Typescript, and MongoDB. Running into issues while trying to deploy it on Heroku. Utilizing the meteor buildpack from jordansissel/heroku-buildpack-meteor. Uncertain whethe ...

Create a dynamic Prisma data call by using the syntax: this.prisma['dataType'].count()

I'm currently working on implementing a counting function that can be utilized in all of my objects. In my 'core' file, Prisma is involved in this process. This allows me to execute commands like this.user.count() or this.company.count() I ...

What is the best way to handle code versioning using Django, Angular2, and Webpack?

Currently, I am utilizing Django in conjunction with Angular 2 and Webpack. Within Django, I have set up a URL to display my application at http://example.com/user/beta. Initially, my index.html file is rendered, which contains my Angular 2 components. Wit ...