Malvinka
Malvinka

Reputation: 1389

Fetched JSON: object or array? iterating

I cannot understand why I can't iterate through my JSON. In service file I fetch the JSON:

getPosts() {
    return this.http.get('https://jsonplaceholder.typicode.com/posts')
}

then I use it in my component:

posts$: Object;

constructor(private data: DataService) { }

ngOnInit() {
    this.data.getPosts().subscribe(
      data => { 
       this.posts$ = data;
    })
}

and I can iterate through it in my html template:

<li *ngFor='let post of posts$'>
    <h3>{{ post.title }}</h3>
</li>

but I cannot do similar in component:

for(let i = 0; i < this.posts$.length; i++)

result with Property 'length' does not exist on type 'Object'.

And as far as I understand that error what I don't understand is why I can iterate through it in html and how it should be coded properly it in my component. Could you help?

Upvotes: 0

Views: 89

Answers (1)

kun
kun

Reputation: 4237

when you do this.data.getPosts().subscribe() and assigning data to this.posts$, you are assigning the actual data(array of posts) to the this.post$ variable, thats why you are able to see the result rendered. To unsubscribe properly what you can do is with the async pipe.

for example: <li *ngFor='let post of (posts$|async)'> <h3>{{ post.title }}</h3> </li> and assign observable directly ngOnInit() { this.post$=this.data.getPosts(); }

Upvotes: 1

Related Questions