I have some code in my controller that was directly calling $http to get data.
Now I would like to move this into a service. Here is what I have so far:
My service:
angular.module('adminApp', [])
.factory('TestAccount', function ($http) {
var TestAccount = {};
TestAccount.get = function (applicationId, callback) {
$http({
method: 'GET',
url: '/api/TestAccounts/GetSelect',
params: { applicationId: applicationId }
}).success(function (result) {
callback(result);
});
};
return TestAccount;
});
Inside the controller:
TestAccount.get(3, function (data) {
$scope.testAccounts = data;
})
How can I change this so rather than passing the result of success back it
passes back a promise that I can check to see if it succeeded or failed?
Make your service to return a promise and expose it to service clients. Change your service like so:
angular.module('adminApp', [])
.factory('TestAccount', function ($http) {
var TestAccount = {};
TestAccount.get = function (applicationId) {
return $http({
method: 'GET',
url: '/api/TestAccounts/GetSelect',
params: { applicationId: applicationId }
});
};
return TestAccount;
});
so in a controller you can do:
TestAccount.get(3).then(function(result) {
$scope.testAccounts = result.data;
}, function (result) {
//error callback here...
});
Related
This question is related to another one.
Before I did added $ionicPlatform, my service working just fine, but now there is something wrong with $http.
Here is example of injectables:
(function () {
"use strict";
angular.module('service', ['ionic'])
.service('BBNService', ["$http", "$localStorage", "$ionicPlatform",
function ($http, $localStorage, $ionicPlatform) {
And using of $http and $ionicPlatform
this.tips = function () {
var url;
$ionicPlatform.ready(function () {
if (window.Connection) {
if (navigator.connection.type == Connection.CELL_4G || navigator.connection.type == Connection.WIFI) {
if (this.getDayId = 0)//If Sunday - retrieve updated tips
url = this.host + "/tips/";
else
url = "data/tips.json";//If not - use saved data
}
}
});
var request = $http({
method: "GET",
url: url
}).then(
function mySucces(response) {
return response.data;
},
function myError(response) {
return response.data;
});
return request;
};
You need to send back the promise, doing a return response.data is not gonna work.
var deferred = $q.defer();
var request = $http({
method: "GET",
url: url
}).then(
function mySucces(response) {
deferred.resolve(response.data);
},
function myError(response) {
deferred.reject(response.data);
});
return deferred.promise;
And at the place where you consume this service:
BBNService.tips().then(
function(data) { //success call back with data },
function(data) { //error call back with data }
);
Please let me know if you need more explanation on using $q; always happy to give more details.
I have 3 services.
HttpSender - It controls the $http request
app.service("HttpSender", ["$http", "$q", function ($http, $q) {
this.send = function (path, method, params) {
var deferred = $q.defer();
$http({
url: path,
method: method,
params: params
}).then(function successCallback(response) {
deferred.resolve(response.data);
}, function errorCallback(response) {
deferred.reject(response);
});
return deferred.promise;
};
this.sendRequestWithFile = function (path, method, params) {
//todo check if needed
};
}]);
Api - controls all the api/ access token processes
service("API", ["HttpSender", "$q", 'WindowOpen', function(HttpSender, $q, WindowOpen){
var self = this;
var API = {};
API.requestTypes = {
GetMethod: "GET",
PostMethod: "POST",
DeleteMethod: "DELETE",
PutMethod: "PUT"
};
API.sendRequest = function (path, method, parameters, isCheckAccessToken)
{
path = ServersConfig.getApiServerUrl() + path;
parameters.access_token = getAccessToken();
HttpSender.send(path, method, parameters);
};
return API;
}]);
Api - Endpoint which activate the api request
app.factory('SelectedEndpoint', ['API',
function (API) {
var getPath = function (campaign) {
return "/campaigns/" + campaign.id + '/content/selected';
};
return {
get: function (campaign) {
API.sendRequest(getPath(campaign), API.requestTypes.GetMethod, {}, true).then(function (content) {
});
}
};
}]);
How can return the deferred.promise to the endpoint function so the then will get the answer? The following process only works if i add then also in the api factory the then return it to the endpoint
How can return the deferred.promise to the endpoint function so the then will get the answer?
By properly returning promises on each step.
1. HttpSender service. Do not use deferred here, just return promise directly:
app.service("HttpSender", ["$http", "$q", function($http, $q) {
this.send = function(path, method, params) {
return $http({
url: path,
method: method,
params: params
}).then(function successCallback(response) {
return response.data;
});
};
}]);
2. Api service. Make sure you return previous promise with return HttpSender.send(path, method, parameters);:
service("API", ["HttpSender", "$q", 'WindowOpen', function(HttpSender, $q, WindowOpen) {
var self = this;
var API = {};
API.requestTypes = {
GetMethod: "GET",
PostMethod: "POST",
DeleteMethod: "DELETE",
PutMethod: "PUT"
};
API.sendRequest = function(path, method, parameters, isCheckAccessToken) {
path = ServersConfig.getApiServerUrl() + path;
parameters.access_token = getAccessToken();
return HttpSender.send(path, method, parameters); // note return promise
};
return API;
}]);
myapp.factory('serviceName', function( $http, webStorage){
var factory = {};
var resoureurlBase=some base url;
factory.genericService = function(method, payload, methodName, callbackFn, callbackError, param) {
var httpRequest = null;
if (param && param == true) {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
params: payload,
headers: {
'Content-Type': 'application/json'
}
});
} else {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
httpRequest.then(function(response) {
if (callbackFn && callbackFn.call) {
callbackFn.call(null, response);
}
},
function(response) {
if (callbackError && callbackError.call) {
callbackError.call(response);
}
});
httpRequest.error(function(data, status, headers, config) {
});
};
return factory;
});
/*
I have written service like above how can i handle in controller
i mean
how to write call back function in controller
how to inject
etc..
*/
Simple DI(dependency injection) it into your controller:-
myapp.controller('myCtrl',['$scope','serviceName',function($scope,serviceName){
// use serviceName to call your factory function
}]);
Ref:- https://docs.angularjs.org/guide/di
You need to call service like
serviceName.genericService(--parmas--).then(function(d){
//success
})
because from service serviceName, you're returning a promise that need to resolved using .then only.
Controller
var mainController = function($scope, serviceName) {
var callbackFn = function() {
console.log('Success');
}
var callbackError = function() {
console.log('Error');
}
var parameter = {
param1: 1
},
method = 'something', payload = 100, methodName = 'something';
serviceName.genericService(method, payload, methodName, callbackFn, callbackError, parameter).then(
//success function
function(data) {
//call after call succeed
},
//error function
function(error) {
//call after call error
});
};
myapp.controller('mainController', ['$scope', 'serviceName', mainController()];
Hope this could help you. Thanks.
I have the following script:
$q.all([
getActive(),
getUser()
])
.then(function (results) {
var x = results[0];
var y = results[1];
}
function getActive() {
$http({
url: '/api/Test/GetActive',
method: "GET"
})
};
function getUser() {
$http({
url: '/api/Test/GetUser',
method: "GET"
})
};
I was expecting to see that the variables x and y would contain the results of the $http calls but they both show as undefined.
Can someone suggest how I can make these calls return a promise. I actually thought $http did return a promise so I am confused.
You seem to be missing the return statement in both the getActive() and getUser() functions.
Try this:
$q.all([
getActive(),
getUser()
])
.then(function (results) {
var x = results[0];
var y = results[1];
}
function getActive() {
return $http({
url: '/api/Test/GetActive',
method: "GET"
});
};
function getUser() {
return $http({
url: '/api/Test/GetUser',
method: "GET"
});
};
Here's a working example. I changed your code in a few small ways. Note: The returned promises from the individual calls, the simplified way of calling $http, and pulling the data out of the returned results in the then() function:
http://plnkr.co/edit/YStkRt?p=info
function MainCtrl($scope, $q, $http) {
$q.all([
getActive(),
getUser()
])
.then(function (results) {
$scope.ip = results[0].data;
$scope.headers = results[1].data;
});
function getActive() {
return $http.get('http://ip.jsontest.com/');
}
function getUser() {
return $http.get('http://headers.jsontest.com/');
}
}
Consider the code:
var myApp = angular.module('myApp', []);
The routes:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'app.html',
controller:myAppController,
resolve:{
resolveData:function(Resolver){
return Resolver();
}
}
});
});
Resolve:
myApp.factory('Resolver', ['$http', function($http){
return function(){
return $http({url: '/someurl',method: "GET"}).then(function(data) {
// dependent call 1
$http({url: '/someotherurl',method: "GET" }).then(function(data) {
});
// dependent call 2
$http({url: '/someanotherurl',method: "GET" }).then(function(data) {
});
});
}
}]);
Above I have nested 2 calls inside one as they are dependent on the data returned by the parent call.
What I want to do: return the Resolver when all of them have completed and not just the parent call.
I cannot use $q.all() because 2 of the calls are dependent of the first call.
In short, myAppController must be loaded only after all the 3 calls have completed.
You should be using chaining promise and $q service to solve your problem .Just use the below sample code it should work
myApp.factory('Resolver', ['$http','$q', function ($http,$q) {
return function () {
var deferred = $q.defer();
$http({ url: '/someurl', method: "GET" }).then(function (data) {
return $http({ url: '/someurl', method: "GET" })
}).then(function (data) {
return $http({ url: '/someanotherurl', method: "GET" })
}).then(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
}]);
This works for me:
resolve : {
message: function($q, $route, Restangular) {
var msgId = $route.current.params.msgId;
var deferred = $q.defer();
Restangular.one('message', msgId).get().then(function(message) {
Restangular.one('file', message.audioFile.id).get().then(function (blob) {
message.blob = blob;
deferred.resolve(message);
});
});
return deferred.promise;
}
}