0

I'm using the Last.fm API to get data for a user, but by the time I'm done getting all the data I need, I end up making a lot of http requests, which can easily get pretty messy.

What I'm doing at the moment is this ( example for only two requests ):

getData(user) {
    return this.$q.all({
        userInfo: this.$http.get(this.rootUrl + '?method=user.getinfo&user=' + user + '&api_key=' + this.apiKey + '&format=json'),
        userTopArtists: this.$http.get(this.rootUrl + '?method=user.gettoptracks&user=' + user + '&api_key=' + this.apiKey + '&format=json')
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

Is there a more cleaner and efficient way of making multiple http requests when we have such a messy URL ?

As above so below
  • 619
  • 1
  • 6
  • 13
  • Make a method to return the URL by passing it its parts. – johnny 5 Nov 08 '17 at 11:52
  • I agree with @johnny5 - in addition, if you're using ES2015 (which, judging by the arrow functions, you probably are), you could make good use of [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) here. – Joe Clay Nov 08 '17 at 11:53
  • @johnny5 Could you give me an example of how the method might look like ? – As above so below Nov 08 '17 at 11:54
  • I'm on my phone so it might be hard but I'll walk you through. You make a resource for each request you can call this file ApiResources. Then store the root path in an environment file so you can easily switch environments. You probably can store your API key there, or alternatively you can create an authentication service for the other resources like the users, apiResources takes in those injected services and automatically builds the urls by requesting that method corresponding to each request. – johnny 5 Nov 08 '17 at 12:00
  • i would create a urlFactory sending the wanted url and the needed parameters, the function will build the url with sub or external func. – Goor Lavi Nov 08 '17 at 12:06
  • Will something like this method do the job ? `buildUrl(method, user) { return `${this.rootURL}?method=${method}&user=${user}&api_key=${this.apiKey}&format=json`; }` – As above so below Nov 08 '17 at 12:13

0 Answers0