问题
I am accessing an API via Angular $http requests to gather information for different football teams.
If I were to be only accessing one team, this would be fine - I would create a Service that made the call, then reference the Service function in my controller. However, I want to do this on numerous teams, without having to create a separate Service module for each one.
Service
app.factory('APIService', ['$http',
function($http) {
return $http.get('http://API/team/1204?Authorization=xxxxx')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
]);
Inside my Controller...
APIService.success(function(data) {
$scope.apiData = data;
});
As you can see in the Service, the team is specific, "1204", and will only pull in the data from that one team. I want to create a function that allows that four digit code to be interchangeable depending on the team, but I don't know how, or where to put it.
Any help would be massively appreciated. Thanks in advance.
回答1:
I built a Generic Angular Service that is the only service you will need in your application.
https://github.com/cullimorer/AngularGenericAPIService
The service contains a number of different methods:
GET (array) - GetListData
GET - GetData
PUT - UpdateData
POST - AddData
DELETE - DeleteData
So, what's special about this? Well, what happens is you can call any endpoint passing in as many parameters as you like. This works a lot like the "string.Format" function in C# where it will take the value of objects specified and insert them into another string. The commonService contains a method called "stringFormat" which replicates this functionality for use by the generic API service.
Let's see how we do this in practice. If you wanted to call a restful API endpoint called "fooBars" passing in an "ID" of 1 to return a single "fooBar", we would do it like so:
return genericService.getData('fooBars/{0}', [1]);
This will call the API with the URL:
"http://localhost/API/fooBars/1"
The second parameter is an array, this way you can pass in as many parameters as you like into the string, let's say we have a number of "foos" and "bars" we might do something like this:
return genericService.getData('foos/{0}/bars/{1}', [1, 2]);
This will call the API with the URL:
"http://localhost/API/foos/1/bars/2"
And so forth. It's a pretty simple service but I use it in all AngularJS projects because it's so easy to implement and means you don't have to write a tonne of different queries in your Angular services or write long string concatenations.
来源:https://stackoverflow.com/questions/36953997/referencing-multiple-api-calls-in-one-service-angular