How to have multiple methods in a module and how to display the result in a template?


#1

I’m new to ionic/angular. I created a rest api for my custom theme taxonomy in wordpress. I created a provider called ads

  retrieveAds() { 
    return this.http.get(this.api_url)
      .map(res => res.json());
  }

  retrieveThumbInAds(adId: number) {
    return this.http.get(this.thumb_url + adId )
      .map(res => res.json());
  }

Then in my home.ts

 ionViewDidLoad() {
    this.adsProvider.retrieveAds().subscribe(results => {
      this.ads = results;
      

    });

     this.adsProvider.retrieveThumbInAds(this.ads).subscribe(results => {   ---> this is wrong, how to correct it?
      this.thumbs = results;
    }); 
  }

Then in my home.html

    <ion-card [@fadeIn]="fade" class="category-card" *ngFor="let item of ads">
        <img src="{{item.shop_thumbnail}}" /> ----> this is wrong
        <ion-icon name="md-heart" (click)="activeLike(item)" [ngClass]="{'activeColor':item.like}" class="like-icon" color="light"></ion-icon>
        <div class="card-title" (click)="goDetailPage(item.detail)" text-uppercase>
          <h4 color="secondary">{{item.title.rendered}}</h4>
          <p color="dark">{{item.price}}</p>
          <p  class="excerpt" [innerHtml]="item.excerpt.rendered">  </p>
        </div>
        
    </ion-card>

I have to problems in my code, the first being I don’t know how to pass the id to the second method, the second problem is how to iterate the thumbnails in the template since they are a different array? should I combine both arrays into one?


#2

Always declare return types of all methods. It will help the build tools help you, and it will help anybody else trying to read the code as well.

For instance, I don’t know what retrieveAds is supposed to be getting. From its name, perhaps an array of ad ids? But then we pass its return to retrieveThumbInAds, which indicates that it may return a single ad id. In that case, it’s poorly named.

If retrieveAds gives a list, and then you are planning on looping through that list and calling retrieveThumbInAds on each element of it, that’s a pretty mangy API, and I would change it to return all the thumbnails at once in retrieveAds, so there is only one HTTP request instead of number-of-ads+1.

A couple of other relatively minor things: if you’re using HttpClient, you don’t need to call res.json(), and it’s a good idea to get in the habit of saying <img [src]="foo"> instead of <img src="{{foo}}">.


#3

Thank you for your tips

  • retreiveAds should return an array like this

http://demo.wp-api.org/wp-json/wp/v2/posts.

That one is for posts, mine is for ads, a custom post type I created in Wordpress.

  • retrieveThumbInAd url should look like this, if I manage to get the id successfully

http://demo.wp-api.org/wp-json/wp/v2/media?per_page=1&order=asc&parent=15

where 15 is the id i got from retreiveAds for example.

then I have to loop through the thumbnails and ads details on homepage