1

I'm building an app similar to Instagram, I'm currently stuck trying to get the likes of a post and I was wondering if someone could help me. I use a Laravel API and it works fine. The problem is that I don't know how to add the likes to my items array.

Here is my code:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {PostsDataProvid`enter code here`er} from '../../providers/posts-data/posts-data';


@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
    providers: [PostsDataProvider]
})
export class HomePage {
    public items =[];
    constructor(public navCtrl: NavController, public getPostsService: PostsDataProvider) {

        this.getPostsService.getAllPosts().subscribe((data) => {
          for(var i=0; i < data.length; i++){
              this.items.push(data[i]);

                this.getPostsService.getPostLikes(data[i].id).subscribe((countLikes) => {
                    this.items[i].likes = countLikes.length; 
                    // if I change countLikes.length with 2 for example it works perfect ( outside this function but within the for loop)
                });
          }
        });
    }
}
Huub
  • 36
  • 9
  • https://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript – Suraj Rao May 23 '17 at 11:25
  • Thanks for your comment but it's not really bringing me any further, could you maybe modify my code really quick to show how its done? If that's possible. Would really, really be appreciated – Huub May 23 '17 at 13:29
  • Change your for loop to the answer..your index value does not remain the same by the time response is returned – Suraj Rao May 23 '17 at 13:33
  • Thanks, I am now able to get the amount of likes per post and include it in the JSON Object, the only problem I'm trying to deal with right now is showing the result in the HTML, all the post objects together are called "data' and each post is a "dataItem" how do I now show it? – Huub May 23 '17 at 14:04

0 Answers0