Extract the JSON array data from the Service and process it within the Component

When passing a response from the Service to the Component for display on the UI, each value needs to be parsed and stored in a variable. This can be achieved by extracting values such as profileId, profileName, regionName, etc. from the response.

[{"profileId":"000234","profileName":"kofi prfl","regionName":"NA  ","fileType":"GRRCN","fileVersion":"1.01","fileFreq":"D01","fileFormat":"FIX","emptyFile":"N","cardMask":"Y","uprInd":"N","dataLevel":"01"}]

this.profileDetailsService.getProfileDetails(this.idDisplay)
      .subscribe(profileResponse => {
          // Parsing of the profileResponse should occur in this section....
          this.searchResult = profileResponse;
          this.spinnerService.hide();
        },
      error => {
          this.spinnerService.hide();
          this.showError();
        }
      );

Is there a way to separate the values for profileId, profileName, regionName, etc.?

Answer №1

Instead of having this snippet in your code:

...
this.searchResult = profileResponse;
...

You could opt for the following approach:

searchResult: any[];

...
this.searchResult = profileResponse.json() || {}
...

After that, you will be able to access each property through the searchResult item:

this.searchResult[0].profileId, etc

Answer №2

Revise following a comment code update:

An issue arises when attempting to access the properties of searchResult due to the service returning a response instead of a Javascript object with defined properties.

The Angular HTTP documentation found here, explains:

The response data is in JSON string format. It needs to be converted into JavaScript objects using response.json().

Recommendation is to parse the response within the service to consolidate all related http request functionalities and avoid redundancy in code.

Previous Code Snippet:

return this.http.post(this._url, body, options).map((response: Response) => {
    return response;
}).catch((error) => {
    return Observable.throw(error);
});

To address this (assuming only the first profile in the array is needed):

 return this.http.post(this._url, body, options).map((response: Response) => {
        return response.json()[0];
    }).catch((error) => {
        return Observable.throw(error);
    });

The updated code now properly parses the JSON object, fetching the initial object from the array utilizing .json()[0]. Alongside, change profileResponse to profileDetails, allowing direct access to this.searchResult's properties through dot notation:

Example usage in another component function:

console.log(this.searchResult.profileName)

Sample template usage: {{searchResult.profileName}}

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

Steps to create a dynamic Datatable using Jquery

Can someone please help me create a dynamic table using Jquery DataTables? I specifically need the table to be of type Server-side processing, where all the columns are generated in the same Ajax request along with the results. DataColumns = "" //JSON res ...

Filling the text and value array using a collection of objects

Need help with populating an array of text and value using an array of objects in Angular. Below is the JSON data containing the array of objects. Declaration public AuditYearEnd: Array<{ text: string, value: number }>; Assignment - How can I assi ...

Having trouble launching my node application on port 80 on Ubuntu 16.04

Trying to run my node app on port 80 in Ubuntu 16.04 is proving to be a challenge. Despite the fact that the port is not in use, when attempting to start my app with npm start, an error message stating "Port already in use" is displayed. According to infor ...

How to Transform the Body-Format of a POST Request in Service Stack

Currently, I am using a RequestClass with the Route annotation to invoke a Json-Client POST method. However, the parameters are structured as follows: public class GetTicketRequest: IReturn<JsonObject> { public string CartId { get; ...

Error: Trying to access the 'checked' property of an undefined variable

Currently, I am working on populating my panel with data from a web API (which is already functioning) while also allowing users to add new points to the list through the panel. This is my checkbox panel: <div class="generalCharacteristicsHover" (mo ...

Creating a Connection between Angular 4 and MySQL Database using PHP for Data Posting

After spending a few weeks searching for the answer to my question, I still haven't found what I'm looking for. I understand that Angular is a front-end framework and that I have freedom to choose any database and backend for my project. Current ...

The parser encountered an unexpected token while attempting to parse the provided string

Struggling to correctly parse a JSON response from a server using node, as it is showing up as a string. Here's an example: "{name:'hello'}" Recreated the issue here: http://jsfiddle.net/x5sup14j/ Tried replace(/'/g, '"'); ...

How is it possible to leverage the CDN URL mechanism for package management when working with Typescript?

Is it possible to use a CDN URL pointing mechanism to resolve packages in Typescript? One example is the Material Icon package installation, which can be included using the following code: <link rel="stylesheet" href="https://fonts.googleapis.com/icon? ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Automatically generate a file path for imports using the class name

When working on my angular 2 application in Visual Studio, I often wish there was a way to automatically populate the import path similar to how C# uses statements work with the 'ctrl .' key combination. Typing out imports repeatedly can be tedio ...

In a local setting, the KendoUI chips are displaying without their borders

I recently tested out the code from kendo on StackBlitz and it worked perfectly: https://i.stack.imgur.com/Nrp2A.png However, when running the same code on my localhost, all the styling for the chip is missing: https://i.stack.imgur.com/1pUH9.png The c ...

Tips for saving multiple pieces of data in a single field with Laravel

Is it possible to save multiple data at once using a simple form? controller $status= new PostTable(); $status->language = $request->language; blade <input type="checkbox" value="hindi" name="language[]" id="language"> Hindi model pro ...

Guide to making a sidebar for your chrome extension using Angular, no need for an iframe

I am currently developing a chrome extension using Angular, and it functions similarly to the MaxAI chrome extension. When the user clicks on the widget, it triggers the opening of a sidebar. Although I have followed a few tutorials to create a sidebar, t ...

React and Express are two powerful technologies that work seamlessly

Here lies the contents of the mighty index.html file <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <s ...

Jenkins is experiencing issues with starting up or reconnecting - It is hanging and displaying a severe error message: unable to properly read the JSON file provided at [/var/lib/jenkins/cb-envelope/envelope.json]

Jenkins: Version 2.89.4-x rolling Encountered slow performance issues with Jenkins due to memory problems. After trying to restart Jenkins using the sudo or usual method, a severe issue was encountered. Eventually, restarted the entire Jenkins machine in ...

Why does Angular throw a NullReferenceException when calling User.FindFirst(ClaimTypes.NameIdentifier), whereas Postman executes the same code without any

I'm currently troubleshooting a NullReferenceException in a .NET Core API and Angular application, but I've hit a roadblock. The specific issue arises when trying to update the "About" section of a User. Take a look at the text area screenshot ...

Guide on removing a key from an object in TypeScript

My variable myMap: { [key: string]: string[] } = {} contains data that I need to modify. Specifically, I am trying to remove a specific value associated with a certain key from the myMap. In this case, my goal is to delete value1 from myMap[Key1]. Despit ...

Converting a string to a data type in Typescript: A beginner's guide

I'm currently in the process of developing various web components, each capable of emitting custom events. To illustrate, here are a couple of straightforward examples: //MyButton emits 'myButtonPressed' with the following details: interfac ...

Encountering a problem when trying to use event.target.value in an Angular TypeScript application

Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...

The correct method for handling arrays with overlapping types and narrowing them down again

When working with arrays containing different types in TypeScript, I often encounter issues with properties that are not present on all types. The same challenge arises when dealing with various sections on a page, different user roles with varying proper ...