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

Prevent users from selecting elements on the mobile site

Hey there! I'm currently working on preventing users from selecting items on my mobile site. While I've been successful in doing so on a regular website using the CSS class below .unselectable { -moz-user-select: -moz-none; -khtml-user-s ...

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

Disabling an HTML attribute on a button prevents the ability to click on it

In my React application, I have a button component that looks like this: <button onClick={() =>alert('hi')} disabled={true}>test</button> When I removed the disabled attribute from the browser like so: <button disabled>test& ...

Guide on extracting unique key values from an array by utilizing a different key

I have an array containing the names of products along with their storage capacities. let products = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storag ...

Hide Decimal Places with Angular Pipe

I am working with a progress bar that can have a progress ranging from 0.1 to 99.999 In the TypeScript file, I prefer not to use the math.round function as it will disrupt the logic. My intention is to display the progress without decimal points, for exam ...

Why does one of the two similar javascript functions work while the other one fails to execute?

As a new Javascript learner, I am struggling to make some basic code work. I managed to successfully test a snippet that changes text color from blue to red to ensure that Javascript is functioning on the page. However, my second code attempt aims to togg ...

Refresh content on an HTML page using information retrieved from an external PHP post request

So, I have a problem with communication between my two web pages - mobile.html and video.php. The idea is for mobile.html to send an AJAX post request containing a single variable to video.php. Video.php should then read this variable and pass it to a Java ...

How do we handle the reception of document.form.submit() in the code behind?

I have a JavaScript function document.form1.submit() and I am wondering how to receive it in the code behind. In which class and method should I be looking? I need to get the value from a textbox and store it in session, but I'm not sure if I need an ...

Error in Vue.js and Socket.io - the server response cannot contain the wildcard '*' when the request has its credentials mode set to 'include'

I'm currently working on creating a chat app using Vue and Socket IO. Here's the error I'm encountering. This is my Node server code. And this is my Vue app code. My Node server and Vue app are separate entities. How can I resolve this i ...

What is the best way to change the date format from "yyyy-MM-dd" in a JavaScript file to "dd/MM/yyyy" and "MM/dd/yyyy" formats in an HTML file?

Is there a way to transform the date string "2020-08-02" from a JavaScript file into the formats "08/02/2020" and "02/08/2020" in an html file, without relying on the new Date() function in JavaScript? I would greatly appreciate any assistance with this t ...

javascript highchart image carousel

I am currently working on a visual chart project using the JavaScript library highchart. After setting up my chart with some dummy data, I am looking to incorporate functionality that allows for triggering an image slide based on the chart data. Specific ...

Leverage the power of Angular 2 components within your Asp.net MVC

I am currently working on an Asp Mvc project which utilizes Angular 1.4 for the frontend. While my project is not designed to be a single page application, I am interested in incorporating Angular 2 without transitioning the entire project into a SPA. Aft ...

Updating the Edit icon within the Mat table is not being properly refreshed when editing inline text

I am currently working on implementing inline editing for a mat table. I found a helpful guide at this link. When I try to edit the second row on page 1 (the edit symbol icon changes), and then move to the next page without saving the changes, the second r ...

Break down the provided Array type into distinct new types

If we have a specific type defined as: type Tuple = [name: string, age: number, address: string]; and we are interested in creating a new type without the first element, like this: type NewTuple = [age: number, address: string]; Is there a way to achieve ...

If an element with a "hidden" display property is loaded in the browser window, will it be visible?

Is an element in a hidden display still using memory when the page is loaded? It's convenient to have many elements on a page, but if 99 elements are hidden and only 1 is displayed, does that impact the loading of the page? I'm curious if the pa ...

Sending information to the styles feature in Angular 2

Is there a way to transfer data from an Angular tag to the styles in the @Component? Take a look at my component: import { Component, Input } from '@angular/core'; @Component({ selector: 'icon', template: `<svg class="icon"> ...

Tips for simulating a "nested" angular service within a component using jest

I'm looking to create a unit test for an Angular Component using Jest. The component, which is built on Angular version 7.2.0, interacts with a nested service through this.api.manageUser.getUsersStats(). My goal is to verify if this method is being ca ...

Divide and conquer- Lighttpd's mod_wstunnel combines separate messages by using UNIX socket communication to the backend server

In my experience with lighttpd's mod_wstunnel, I have encountered a peculiar issue. When I send two messages in quick succession from the backend using a UNIX socket to communicate between lighttpd and the backend, I noticed that lighttpd logs show th ...

What is the best way to implement the Active list element feature in my menu bar?

The current list element is : <li class="nav__item"><a class="nav__link nav__link--active " href="#"... The standard list element is: <li class="nav__item"><a class="nav__link " href=&quo ...

Sending dynamic information to bootstrap's modal using props in VueJS

I'm currently working on a personal project and encountering an issue with the bootstrap modal. My project involves a list of projects, each one contained within a card element. The problem arises when I attempt to display details for each project by ...