Ian
Ian

Reputation: 181

Reading and iterating though a JSON object angular

I am writing an angular website and I am new to the platform. I am trying to get data from a web service in JSON format then just output it. I have seen many examples where the data is first piped into an array of a class/model. But I would like to know if there is an easier way where I do not have to do this extra data structure. (This is a really simple application)

In my typescript class:

export class TestimonialsComponent implements OnInit {

  public testimonials: Observable<any[]>;
  baseUrl = 'http://127.0.0.1:80/';

  constructor(private httpClient: HttpClient){}

  ngOnInit() {
  }

  get_testimonials(){
      this.httpClient.get(this.baseUrl).subscribe((res : any[])=>{
      console.log(res);
      this.testimonials = res;
      });
  }

And in the HTML file

<button (click)="get_testimonials()">GET /products</button>



<li *ngFor='let testimonial of testimonials | async'>
  {{ testimonial.Name }}
</li>

The console successfully sees my object but I get this error message when I try to do the iteration:

ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

Upvotes: 0

Views: 81

Answers (3)

Ajit Nikam
Ajit Nikam

Reputation: 101

The Error you are getting because of Async pipe

To know more about Async Pipe visit below link https://angular.io/api/common/AsyncPipe

Make Below changes in your code:

In typescript file:

 public testimonials: any[];

In Html file:

<li *ngFor='let testimonial of testimonials'>
    {{ testimonial.Name}}
</li>

Upvotes: 1

Jens Alenius
Jens Alenius

Reputation: 1931

Or you could use your code without the async pipe.

<li *ngFor='let testimonial of testimonials'>
  {{ testimonial.Name }}
</li>

There are benefits and drawback in both approaches. I found that without sync I have more control on error handling and loading indicators. But I suspect it can be solved with async to. Tip: get_testimonials should be written getTestimonials

Upvotes: 0

iams0nus
iams0nus

Reputation: 492

enclose the testimonials | async into a parentheses which is much cleaner code

let testimonial of (testimonials | async)

and in the service do not subscribe to the http observable. the testimonials property should be an Observable.

get_testimonials(){this.testimonials = this.httpClient.get(this.baseUrl)};

the async will automatically subscribe and get the testimonials.

Upvotes: 0

Related Questions