0

I am trying to convert a json response into an array in angular 2. The following is the code i have used,

.ts file

  response;
  resp;
  constructor(private http:Http) {
   }
   get()
   {
         this.http.get("http://localhost:3000/items")
         .map(res=>res.json())
         .subscribe(data=>this.response = JSON.stringify(data))

           this.resp = JSON.parse(this.response);
      }

component.html

 {{response}}
 <ul>
    <li *ngFor="let k of resp">{{k}}</li>
  </ul>

</div>

Although the {{response}} simply results in the whole json content getting displayed, i am unable to iterate through the response retrieved in resp despite using JSON.parse().

How can I convert the response to an array and access the individual properties ?

1
  • Can you give me console output of this.response ?? Commented Dec 18, 2017 at 5:17

2 Answers 2

0

As per your code I can not see you are setting resp variable.

You are storing value in response variable and iterating on resp variable.

It should be (let k of response) instead of (let k of resp)

Sign up to request clarification or add additional context in comments.

Comments

0

You can only iterate arrays using ngFor. If your response is an json object then you can not directly iterate it using ngFor. For that you need to use a pipe to iterate the json object through ngFor.

You can create a pipe.

@Pipe({ name: 'keys',  pure: false })
export class KeysPipe implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)
    }
}

Import this pipe in your module and pass it in the declrations. Then you can use it in your html like this:

 {{response}}
 <ul>
    <li *ngFor="let k of resp | keys">{{k}}</li>
  </ul>

</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.