Poonkodi Sivapragasam
Poonkodi Sivapragasam

Reputation: 1317

Parse the JSON array object from the Service in the Component

This is the response I am passing from the Service to the Component where i should display each value to the UI. I need to parse each value and store to a variable.

[{"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 => {
          // Should parse the profileResponse here....
          this.searchResult = profileResponse;
          this.spinnerService.hide();
        },
      error => {
          this.spinnerService.hide();
          this.showError();
        }
      );

How to separate profileId, profileName, regionName etc., values?

Upvotes: 2

Views: 13407

Answers (2)

SpaceFozzy
SpaceFozzy

Reputation: 2808

Update based on comment code:

The reason you're not able to access the properties of searchResult is that the service is returning a response rather than a Javascript object with properties.

From the HTTP Angular docs here:

The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().

I suggest parsing the response in the service to keep things related to the http request there and prevent code duplication.

Change:

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

To this (if indeed you only want the first profile in the array):

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

The new code parses the JSON object and extracts the first object from the array with .json()[0]. Then rename profileResponse to profileDetails and access this.searchResult's properties using dot notation:

e.g. From another function in the component: console.log(this.searchResult.profileName)

e.g. From your template: {{searchResult.profileName}}

Upvotes: 0

Joseph Wu
Joseph Wu

Reputation: 5028

instead of in your code:

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

you can use:

searchResult: any[];

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

then you can access each property via searchResult item:

this.searchResult[0].profileId, etc

Upvotes: 2

Related Questions