Reputation: 21
I am trying to develop a component that makes a variable number of AJAX requests, to different URL's. Here is what it does:
Make an initial request to get the groups to which the user belongs.
When the initial request completes, make a request for each group returned. The URL for the request includes the group id returned in the response to the initial reqest.
As each group request completes, and the group data to an array property.
When all of the group requests have completed, set a Boolean property so that the "loading" indicator becomes hidden.
This is straightforward to do with jQuery. You just call $.ajax for each group in step 2. For step 4 you pass all of the Deferred objects returned by the $.ajax calls to $.whenAll.
It's clear how to do step 1 with iron-ajax. I am looking for an example of how to accomplish steps 2 and 4 in Polymer. All of the iron-ajax examples I have seen do one ajax request to a service whose URL is hard coded. How do you do a variable number of request, where the URL's are determined at run time?
Thanks, Dennis
Upvotes: 0
Views: 362
Reputation: 3662
First of all, and I would encourage that path, you are not limited to working with Polymer in a declarative way. You could easily write code similar to $.ajax with the fetch API and Promises. Basically there's window.fetch
instead of $.ajax
and Promise.all
instead of $.whenAll
.
MDN states it's not yet standardized, but the polyfill implementations do offer a stable solution.
If you really want to use iron-ajax
, you can bind it with dynamic values and iterate the result inside a dom-repeat
.
<iron-ajax url="[[groupsUrl]]"
auto
handle-as="json"
last-response="{{userGroups}}"></iron-ajax>
<template is="dom-repeat" items="[[userGroups]] as="group">
<iron-ajax url="/api/base/url/{{group.id}}"
auto
on-response="handleGroup"></iron-ajax>
</template>
Finally, in the handleGroup
function you can populate the array property. Setting the boolean loading flag will be icky though. The only way for you to tell that all requests have finished is by counting how many time the handleGroup
event handler fires. Promise.all
is definitely cleaner in this regard.
Upvotes: 1