Outputting undefined values when processing an http post array

I seem to have encountered a major issue. Despite my efforts, I am seeing an undefined value when trying to display this JSON data.

{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }

The code snippet in my service.ts file looks like this:

public getHomeboxPById(id: string): Observable<HomeboxP> {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('home_id', id);
    urlSearchParams.append('token', this.auth.getCurrentUser().token);
    let body = urlSearchParams.toString();
    return this.http.post(Api.getUrl(Api.URLS.getHomeboxPById), body, {
    headers: headers
    })
    .map((response: Response) => {
        let res = response.json();
        if (res.StatusCode === 0) {
         return new HomeboxP(res.StatusDescription[0]);
        } else if (res.StatusCode === 1) {
         this.auth.logout();
        } else {
           return new HomeboxP(null);
        }
    });
}

In the TypeScript code, I invoke the getHomeboxPById method as shown below:

editHomeboxPForm: FormGroup;
homeboxp: HomeboxP;
this.editHomeboxPForm = this.fb.group({
      'homebox_id': new FormControl('', Validators.required)
});

populateFormHomeboxP() {
    this.activatedRoute.params.subscribe(
    params => {
    this.ws.getHomeboxPById(params['id']).subscribe(
     homeboxp => {
        console.log(homeboxp);  // displays undefined
        this.homeboxp = homeboxp;
        this.editHomeboxPForm.controls['homebox_id'].setValue(homeboxp.homebox_id);
        }
      );
     }
   );   
}

I'm seeking your assistance in understanding why this is not functioning correctly. Can you offer any help?

Answer №1

{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }

If this is the output of

this.http.post(Api.getUrl(Api.URLS.getHomeboxPById)

The problem lies in res.StatusDescription[0] , it should be res.StatusDescription as shown below:

new HomeboxP(res.StatusDescription);

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 opacity of each div within a container increases as you move from one div to the

I am striving to craft a series of divs that feature varying levels of opacity in their background colors, creating a gradient effect. In an attempt to achieve this, I utilized a variable linked to the ID of each individual div. Unfortunately, my efforts ...

Pausing or buffering an RxJS 6 observable when the page is inactive

Currently, I am dealing with a stream of letters that need to be arranged in the correct order to form a word. However, an issue arises when the user switches tabs, minimizes the browser, or switches applications - the behavior mimics using setTimeout(), r ...

Utilizing Gson to send a JSON message on an Android device

Looking to transmit a json message via http to a php server. Utilizing the gson library, as shown in the code snippet below: Gson gson = new Gson(); String[] data = {"value1", "value2", "value3"}; String json = gson.toJson(data); String message = "jdata"+ ...

What is the best way to fetch the id of the option that has been chosen from a bootstrap drop-down menu?

I recently created a basic drop-down list like this: https://i.sstatic.net/4Tlxx.png Here is the HTML code for it: <select class="form-control" id='0' (change)="retrieveValue($event.target)"> <option id='0'>{{ g ...

Changing spaces to plus signs within a PHP arrayOrConverting

I have retrieved an array called $allprofessions from the database Array ( [0] => Html css js [2] => web developer [3] => fitness trainer) I need to replace all spaces in the array ' ' with '+'. The desired output should be: ...

Dealing with a missing item in local storage in an Angular application

When working with local storage, I have a function that saves certain values and another method that reloads these values. However, what is the best approach to handle missing items in the local storage? This could happen if a user deletes an item or if it ...

Finding the total number of nodes within a JSON string is a straightforward process that involves analyzing the

Can the number of nodes in a JSON be calculated using SQL? { "File":[ { "ID":1, "Fragment":"Frag1" }, { "ID":2, "Fragment":"Frag2" }, { "ID":3, "Fragment":"Frag3" }] } Is it possible to determine the ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Converting a JSON string containing multiple fields into a dictionary object

Looking for a solution to parse a complex JSON string: { "PropertyInfos": [ { "Identification": { "IDValue": "102" }, "PropertyName": "Casa Bella", "Mana ...

Is it better to use a setter instead of an isMethod with @JsonIgnore in JSON serialization and

Here is a snippet of my custom HouseJPAImpl class: public class HouseJPAImpl implements House { public RoomJPAImpl room; public RoomJPAImpl getRoom(){ return this.room; } public void setRoom(RoomJPAImpl room){ this.room = room; } @Override public bool ...

Display the HTML string as regular text in an Angular application

I'm working on a blog project with Angular. I need to display HTML content retrieved from the database as plain text for each blog post preview. The HTML formatting was done with ngx-quill. While I can render the rich text using <quill-view [conte ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

What is the best way to set up a JSON attribute with properly formatted JSON data?

Within this code snippet, the variable some is assigned a JSON string that requires expansion and proper indentation for improved readability. export class MyComponent implements OnInit { some:any = JSON.parse('[{"id":"EN","fill":"blue","classb ...

How come the path alias I defined is not being recognized?

Summary: I am encountering error TS2307 while trying to import a file using an alias path configured in tsconfig.json, despite believing the path is correct. The structure of directories in my Angular/nx/TypeScript project appears as follows: project |- ...

Loading JSON Data into Django Models: A Step-by-Step Guide

I have a challenge loading the JSON data below into my Model. { "99popularity": 79.0, "director": "William Cottrell", "genre": [ "Animation", " Family", " Fantasy", " Musical", " Romance" ], "imdb_score": ...

Using React to make an API call without utilizing hooks

Hello, I am currently working on developing a webpart using SharePoint and React. However, I am facing some issues with fetching data from a simple API. export default class Testing100 extends React.Component<ITesting100Props, {}> { constructor(p ...

Combining TSQL with JSON object arrays for joining properties

I am currently working with a stored procedure that takes in a JSON string and uses data from OPENJSON() for insertion. Within my JSON string, there is an object containing a string array. At the moment, I am directly writing the raw JSON of prop2 to my ...

Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I ...

Compulsory Element in JSON Schema

For a project I'm working on, I want to implement JSON-schema validation and have a question about the "required" field. The current documentation states: The value of this keyword MUST be an array. This array MUST have at least one element. Eleme ...

Is it possible to create a child route with parameters that point to components within a lazily-loaded module?

Here is my app.routing.module setup: { path: 'dashboard', component: DashboardComponent }, { path: 'reports', loadChildren: () => import('./reports/reports.module').then(m => m.ReportsModule) The routes for the lazy-loa ...