Upon receiving data from the Api, the data cannot be assigned to the appropriate datatype within the Angular Object

I am encountering an issue with the normal input fields on my page:

https://i.stack.imgur.com/qigTr.png

Whenever I click on the "+" button, it triggers an action which in turn calls a service class with simple JSON data. My intention is to set selectionCustomOffice.custOfficeName to the value of the JSON data's custOffcName, but unfortunately, I keep getting an undefined result.

addedO(selectionCustomOffice: SelectionCustomOffice) {
     this.scoe = true;

   this.selectionCustomOfficeService.getSingleCustomOffice(selectionCustomOffice.customOfficeId).subscribe((data)=> {
        console.log("entered");

         selectionCustomOffice.custOfficeName = data.custOffcName;
         console.log(selectionCustomOffice.custOfficeName);
          }, (error)=> {
         console.log(error);
       });

 this.empList.push(selectionCustomOffice);
 this.selectionCustomOffice = new SelectionCustomOffice();

 console.log(this.empList);
}



this.selectionCustomOfficeService.getSingleCustomOffice(selectionCustomOffice.customOfficeId).subscribe((data)=> {
        console.log("entered");

         selectionCustomOffice.custOfficeName = data.custOffcName;
         console.log(selectionCustomOffice.custOfficeName);
          }, (error)=> {
         console.log(error);
       });

https://i.stack.imgur.com/AMZVN.png

SelectionCustomOffice.ts

export class SelectionCustomOffice {
    id: number;
    fromDate: string;
    toDate: string;
    consignmentNo: number;
    selectionId: number;
    customOfficeId: number;
    custOfficeName: string;

}

The form for sending data looks like this, with the custom office field as a select dropdown:

<div class="form-group row">
   <div class="col-md-4">
      <label>Custom Office</label>
   </div>
   <div class="col-md-2">
      <label>From Date</label>
   </div>
   <div class="col-md-2">
      <label>To Date</label>
   </div>
   <div class="col-md-4">Consignment No</div>
   <div class="col-md-4">
      <select class="form-control" id="customOfficeId" required [(ngModel)]="selectionCustomOffice.customOfficeId" name="customOfficeId"
      >
      <option *ngFor="let title of customoffices" [value]="title.custOfficeId">{{title.custOffcName}}</option>
      </select>
   </div>
   <div class="col-md-2">
      <input type="date" class="form-control" id="fromDate" required [(ngModel)]="selectionCustomOffice.fromDate" name="fromDate" />
   </div>
   <div class="col-md-2">
      <input type="date" class="form-control" id="toDate" required [(ngModel)]="selectionCustomOffice.toDate" name="toDate" />
   </div>
   <div class="col-md-3">
      <input type="number" class="form-control" id="consignmentNo" required [(ngModel)]="selectionCustomOffice.consignmentNo" name="consignmentNo">
   </div>
   <div class="col-md-1">
      <button type="button" (click)="addedO(selectionCustomOffice)">+</button>
   </div>
</div>

Service Class

getSingleCustomOffice(id: number): Observable<any> {
    return this.http.get(`${this.baseUrl}/${id}`, { responseType: 'text' });
  }

Answer №1

It seems like there is a minor issue at hand - You seem to be interpreting your response as text

getSingleCustomOffice(id: number): Observable<any> {
    return this.http.get(`${this.baseUrl}/${id}`, { responseType: 'text' });
  }

You can fix this by either removing the { responseType: 'text' } from the http call or using JSON.parse(data) when handling the data - with { responseType: 'text' }, your response will be in the form of a string

If you prefer your response as text, you can try the following approach:

this.selectionCustomOfficeService.getSingleCustomOffice(selectionCustomOffice.customOfficeId).subscribe((data)=>{
        console.log("entered");
         let outPut = JSON.parse(data);
         selectionCustomOffice.custOfficeName=outPut.custOffcName;
         console.log( selectionCustomOffice.custOfficeName);
          },(error)=>{
         console.log(error);
       });

This adjustment should help resolve the issue - Happy coding !!

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

What steps do I need to take to implement AJAX form authentication?

I have set up a login screen that validates username and password credentials through a php script. When a user enters their information and submits the form, the authenticate.php file executes an LDAP bind. If the credentials are correct, the user is redi ...

Interact with Dialogflow using fulfillment to retrieve responses by opening an HTTP URL

Despite my efforts, I have yet to find a satisfactory solution. I am in the process of creating an agent on Dialogflow. This agent will be embedded on a webpage, not as part of Facebook Messenger or Google Assistant. The purpose of this agent is to guide ...

Issue encountered: Unable to locate module due to error: Unable to resolve 'crypto' in 'C:UsersmonkeDocumentsEpiconesb-ui ode_modules eflect-metadata'

I am encountering an issue with the reflect-metadata package while working on Angular 13. When attempting to use reflect-metadata, I am getting a strange error message stating "Module not found: Error: Can't resolve 'Crypto' in '*\ ...

How can a Chrome extension automatically send a POST request to Flask while the browser is reloading the page?

I am looking to combine the code snippets below in order to automatically send a post request (containing a URL) from a Chrome extension to Flask whenever a page is loading in Chrome, without needing to click on the extension's icon. Is this feasible? ...

How can I make AWS SDK wait for an asynchronous call to finish executing?

Understanding the AWS SDK documentation can be a bit confusing when it comes to making asynchronous service calls synchronous. The page at https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html states: All ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

Various colored backgrounds in a random arrangement on a grid post layout

I'm looking to implement this plugin for displaying blog posts, but instead of using an image as the background, my client wants different colored images. I have managed to figure out the code to achieve this based on a post I found here, but unfortun ...

What is the best way to access JavaScript built-ins in Typings when faced with name conflicts?

I am currently in the process of updating the Paper.js Typings located on GitHub at this repository: github.com/clark-stevenson/paper.d.ts Within Paper.js, there exists a MouseEvent class, which is not an extension of JavaScript's MouseEvent, but ra ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Unable to mock ESM with unstable_mockModule

In my project, I am utilizing ESM. The transpiled .ts files are converted into .js and stored in the 'dist' directory. Here is an example of how my directory structure looks: dist/ ├─ src/ │ ├─ store/ │ │ ├─ index.js │ ├ ...

Learn the process of extracting data from dynamically generated elements in JavaScript

I am a beginner in Javascript and Jquery and have recently started exploring business rules with Chris Powers. https://github.com/chrisjpowers/business-rules My current project involves adding a range slider for numbers and a number spinner. I attempted us ...

Experiencing a problem when attempting to activate the html5 mode feature in AngularJS to eliminate the #

I've been scouring through various sources like stackoverflow and the web, but I haven't found a clear answer to my question. Can someone please help me out? Here's what I'm struggling with: In my AngularJS application, I enabled &apos ...

The iPad screen displays the image in a rotated position while it remains

Recently, I developed a mini test website that enables users to upload pictures and immediately see them without navigating back to the server. It seemed quite simple at first. $('input').on('change', function () { var file = this. ...

Exploring Angular 5 Localization

I am new to the concept of locales. I recently created an Angular 4 app that reads the locale from the browser using the navigator.language() API and provides it to Angular's pipes. However, with the changes in v5, I have some questions regarding migr ...

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...

Tips for saving HTML code within a concealed field utilizing jQuery

What is the best way to store a string with HTML tags in a hidden field using jQuery? I am attempting to use this code, but it's not functioning as expected: var terms = $('#TermsAndCondition').val(); alert($('#hdnTerms').val( ...

Stanza.io encountered difficulties in generating a WebRTC answer

I have successfully set up a realtime messaging website using ejabberd + stanza.io. Everything works perfectly, and now I want to integrate Webrtc audio/video using the jingle protocol. Below is the JS code I am using for connection: var client = XMPP.cre ...

The code within $(document).ready() isn't fully prepared

Feeling frustrated after spending hours searching and attempting to refactor one of my old modules on a rendered Mustache template. It's like diving into code chaos. <section id="slideShow"> <script id="slideShow-template" type="text/tem ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...