# Displaying dynamic API results in a span

**URL:** <https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008>\
**Category:** ionic-v3\
**Created:** [October 7, 2019, 8:27pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008 "2019-10-07T20:27:19Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![winningtech](https://avatars.discourse-cdn.com/v4/letter/w/3ec8ea/32.png) [@winningtech](https://forum.ionicframework.com/u/winningtech)\
**Post date:** [October 7, 2019, 8:27pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/1 "2019-10-07T20:27:19Z")

</div>

I’m getting a list (I’m calling it a collection) from an API, so there’s no telling how many items are in that list. Each list item has sub-items. I’m trying to display the quantity of sub-items next to the quantity of list items.

Something like “3 of 9”

I have the quantity of list items, and am able to get the quantity of sub-items, I just can’t figure out how to display them in the UI.

I was thinking I could create an array of items and use the collection ID as the key, but that doesn’t seem to be working.

## collections.page.html

```auto
<ion-card *ngFor="let collection of collections">
    <ion-card-header>
        <ion-row>
            <ion-col>
                {{ collection.name }}
            </ion-col>
            <ion-col>
                <!-- DISPLAY THE VALUE FROM GETDATA() HERE -->
               <span name="fieldName" ngDefaultControl [(ngModel)]="collection[collection.id]"></span> 
                of {{ collection.items.length || '0' }}
            </ion-col>
        </ion-row>
    </ion-card-header>
</ion-card>

```

## collections.page.ts

```auto
collections: any;
quantity = [];

constructor(public http: HttpClient,private storage: Storage) {
    this.getData();
}

getData() {
    return this.storage.get('token').then(token => {
        if (token) {
            this.http.get('http://api.example.test/collections?api_token=' + token)
                .subscribe((result: any) => {
                    this.collections = result.data.collections;
                    for (const collection of result.data.collections) {
                        const quantity = [];
                        quantity[collection.id] = 0;
                        for (const item of collection.items) {
                            if (item.myitems.length) {
                                for (const myitem of item.myitems) {
                                    quantity[collection.id]++;
                                }
                            }
                        }
                        if (quantity[collection.id] > 0) {

                            // SHOW THIS VALUE IN THE SPAN
                            collection[collection.id] = quantity[collection.id];

                        }
                    }
                }, error => {
                    console.warn(error);
                });
        }
    });
}

```

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [October 7, 2019, 8:36pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/2 "2019-10-07T20:36:36Z")

</div>

Can you explain why we are trying to treat a `span` as a form control, instead of just saying something like `<span [innerText]="whatever"></span>`?

As for your question, whenever you are looping with `ngFor` and want something to be tied to the iteration of the loop, it’s virtually always cleanest to put the thing you want as a property on the loop variable, so that you can write `collection.count` or something to that effect. In this particular case, though, I would back up and put the entire string that is going to end up in the template (“4 of 9” or whatever) in that slot - that should be the final value of `collection.displayCount` that goes in the template. The reason for that is that it will make localization to other languages doable; whereas you have locked yourself into English as things stand currently.

---

<div class="post-metadata">

**Author:** ![winningtech](https://avatars.discourse-cdn.com/v4/letter/w/3ec8ea/32.png) [@winningtech](https://forum.ionicframework.com/u/winningtech)\
**Post date:** [October 7, 2019, 8:50pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/3 "2019-10-07T20:50:07Z")

</div>

I was treating it as a form control because I didn’t know about innerText until now, and if I didn’t use the form control it would throw an error that I had to use it as a form control. I’ve removed it and replaced it with innerText and everything is working. Thank you!

---

<div class="post-metadata">

**Author:** ![winningtech](https://avatars.discourse-cdn.com/v4/letter/w/3ec8ea/32.png) [@winningtech](https://forum.ionicframework.com/u/winningtech)\
**Post date:** [October 7, 2019, 11:15pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/4 "2019-10-07T23:15:23Z")

</div>

I’m trying to do the same thing elsewhere but this time it’s not working. Can you spot what I’m doing wrong?

```auto
<ion-note slot="end" *ngFor="let myitem of item.myitems">
    <span [innerText]="item[item.id]"></span>
</ion-note>

```

```auto
.subscribe(
    (response: any) => {
        const item = [];
        item[itemId] = response.data.item_quantity;
        console.log(item[itemId]); // <- shows the correct value
    },
    error => {
        // toast notification
        this.presentToast('Oops!');
    }
);

```

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [October 7, 2019, 11:24pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/5 "2019-10-07T23:24:00Z")

</div>

> [@winningtech](#):
>
> Can you spot what I’m doing wrong?

Failing to give your variables more descriptive names, which means that they tend to all blur together in a confusing soup of `item` and `myitem` (those two are mixed up in the template).

---

<div class="post-metadata">

**Author:** ![winningtech](https://avatars.discourse-cdn.com/v4/letter/w/3ec8ea/32.png) [@winningtech](https://forum.ionicframework.com/u/winningtech)\
**Post date:** [October 8, 2019, 12:21am UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/6 "2019-10-08T00:21:35Z")

</div>

You’re right. I’ve taken courses on Ionic and Angular, but none of this was taught, so I’m kind of throwing this stuff up to see what sticks. The span is actually supposed to show `myitem.quantity`, so I’m actually not sure why it was showing the correct value with `item[item.id]`. Basically, what I need to do is update the span with the item’s quantity after an update to the API. In the code I showed, `response.data.item_quantity` is the new quantity returned from the API. so I just need to get that value into the span.

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [October 8, 2019, 6:02pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/7 "2019-10-08T18:02:29Z")

</div>

It might sound silly, but I would spend some time away from the Angular bit defining the shape of the domain objects you’re dealing with. No more `data`, no more `item`, no more `any`.

```auto
export interface Treat {
  id: string;
  flavor: "sweet" | "savory";
  calories?: number;
  label: string;
}

export interface TreatBag {
  id: string;
  treats: Treat[]
}

```

Now get all the http junk out of the page and into a service that provides domain objects. If you have to massage what comes over the wire from the API, do it here. If you need other types of slices aside from “all available bags”, such as `getBagById()`, define it here.

Centralize all the business with API tokens and backend servers into an interceptor. An example that you should be able to adapt:

```auto
class AuthService {
  peek(): Promise<string> {...}
}

class ServerService {
  server: Promise<string>;
}

class AuthHttpInterceptor implements HttpInterceptor {
  constructor(private auther: AuthService, private serverer: ServerService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(Promise.all([this.serverer.server, this.auther.peek()])).pipe(
      mergeMap(([server, jwt]) => {
        let tochange: { url?: string, setHeaders?: { Authorization: string } } = {};
        if (server) {
          tochange.url = server + req.url;
        }
        if (jwt) {
          tochange.setHeaders = {Authorization: "Bearer " + jwt};
        }
        let areq = req.clone(tochange);
        return next.handle(areq);
      }));
  }

```

This uses JWT, but you can use `HttpParams` to throw things in the query string as you are doing now. Look at how amazingly streamlined this can make the service: everything that is currently being done in `getData()` collapses into a single simple line:

```auto
export class TreatService {
  allTreatBags(): Observable<TreatBag[]> {
    return this.http.get("collections");
  }
}

```

Now that we can see the forest for the trees, we go back to the page and hopefully the path ahead is crystal clear:

```auto
export class TreatPage {
  bags: TreatBag[] = [];
  constructor(private treater: TreatService) {
    this.treater.allTreatBags().subscribe(bags => this.bags = bags);
  }
}

```

```auto
<ion-note *ngFor="let bag of bags">{{bag.treats.length}}</ion-note>

```

Next up we may have “what do I do when the page’s copy of the data gets stale?”, for which I would recommend [this post](https://forum.ionicframework.com/t/ionic-4-tab-to-page-then-back-to-tab-did-not-trigger-ionviewwillenter-solved/167922/11).

---

<div class="post-metadata">

**Author:** ![winningtech](https://avatars.discourse-cdn.com/v4/letter/w/3ec8ea/32.png) [@winningtech](https://forum.ionicframework.com/u/winningtech)\
**Post date:** [October 10, 2019, 4:08pm UTC](https://forum.ionicframework.com/t/displaying-dynamic-api-results-in-a-span/175008/8 "2019-10-10T16:08:08Z")

</div>

Thank you very much, I read this the other day and took a good look at what I was doing. Decided to go back to square one and follow your suggestions; app is now working like a dream, 🙂
