James Wayne James Wayne - 2 months ago 7
AngularJS Question

Is it possible to pass parameter to $http factory that returns dataReturn?

here is a set up for me to call a php script to get data from an external API. What I did is to set up a factory like such:

app.factory('loadAPI', function ($http) {
var doRequest = function() {
return $http({
method: 'JSON',
url: 'api.php'
});
};
return {
dataReturn: function() { return doRequest(); }
};
});


And then inside my
.controller
I use the following script to process data:

loadAPI.dataReturn().success(function(data, status){

...

}


Now since the external API provides many interfaces, I like to pass parameter to the
.factory
so it can process multiple different type of interfaces (instead of creating multiple
.factory
to process them).

Here is my concept:

loadAPI.dataReturn(parameter).success(function(data, status){

...

}

app.factory('loadAPI', function ($http) {
var doRequest = function(parameter) {
return $http({
method: 'JSON',
url: 'api.php?p=' + parameter
});
};
return {
dataReturn: function(parameter) { return doRequest(parameter); }
};
});


It didn't work.

Answer

The concept would work. I tried it and it returns data correctly. There perhaps are easier ways to pass the parameter to $http. I suspect something wrong with your api.php not reading the parameter correctly.