how do i get the response from $http in from a function in a module?
Angular module:
// module customServices
var customServices = angular.module("customServices", []);
// object for response
httpResponse = {content:null};
// function sendRequest
function sendRequest(param)
{
// inject $http
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
// set header
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http({
// config
method: 'POST',
url: 'response.php',
data: $.param(param),
// success
}).success(function (response, status, headers, config) {
httpResponse.content = response;
// error
}).error(function (response, status, headers, config) {
console.warn("error");
});
}
// factory - moduleService
customServices.factory("moduleService", function () {
return {
// function - members
members: function(param)
{
switch(param.fc)
{
// getAll
case 'getAll':
sendRequest({
service :'members',
fc : param.fc,
id : param.id
});
return httpResponse;
}
},
};
});
Controller:
myApp.controller('main', ['$scope', '$http', 'moduleService', function($scope, $http, moduleService){
$scope.handleClick = function () {
var ReturnValue = moduleService.members({
fc:'getAll',
id:'123',
});
console.log(ReturnValue);
};
}]);
the object is on the first click empty and on the second click its content is the $http response.
but i want that the controller knows when the $http response is available.
i tried to use $broadcast and $on, but it seems to be impossible to use $rootScope in my function "sendRequest".
A couple of things:
Why are you defining the httpResponse instead of just returning something from the sendRequest function?
Why are you defining a function outside angular instead of putting it as a service or factory?
You should create a service with the sendRequest method inside like this:
customServices.factory("yourNameHere", function($http, $q) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
return {
sendRequest: function sendRequest(param) {
return $http({
method: 'POST',
url: 'response.php',
data: $.param(param),
})
.then(function(response) {
return response;
})
.catch(function(response) {
console.warn("error");
return $q.reject(response);
});
}
};
});
Then in the other service:
customServices.factory("moduleService", function (yourNameHere) {
return {
// function - members
members: function(param)
{
switch(param.fc)
{
// getAll
case 'getAll':
return yourNameHere.sendRequest({
service :'members',
fc : param.fc,
id : param.id
});
}
},
};
});
Now the result will be a promise, so you can consume the data like this:
moduleService.members({
fc:'getAll',
id:'123',
})
.then(function(result) {
console.log(result);
});
Related
I have created this service.
and using **enrollments.getProperty();**this statement to call this service but it's not working I'm new to angular-JS please let me know where I making the mistake.
var helloAjaxApp = angular.module("myApp", []);
helloAjaxApp.service('enrollments', [ '$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment=function () {
$http({
url : 'enrollments',
method : "GET"
}).then(function(response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function(value) {
enrollments = value;
}
};
}]);
use angular.module()
(function () {
'use strict';
angular.module("helloAjaxApp")
.service('enrollments', ['$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment = function () {
$http({
url: 'enrollments',
method: "GET"
}).then(function (response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function (value) {
enrollments = value;
}
};
}]);
});
Angular has 2 ways of defining a service: service and factory.
here you can see the difference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
The basic difference is that service is like a constructor, so you don't return an object from it but define the properties using this keyword:
this.getProperty = function () {
return enrollments;
}
When using the factory method, is expects an object to be returned with the exposed properties/functions.
You are using the factory syntax, so just change the definition to use factory:
helloAjaxApp.factory('enrollments', [ '$scope', '$http', function ($scope, $http)
You should go for a proper service structure like so:
var helloAjaxApp = angular.module("myApp", []);
function EnrollmentService($scope, $http) {
let _this = this;
this.enrollments = null;
this.getEnrollments = function() {
return $http({
url: 'enrollments',
method: 'GET'
}).then(function(response) {
_this.enrollments = response.data;
return _this.enrollments;
})
};
this.setEnrollments = function(enrollments) {
_this.enrollments = enrollments;
}
}
helloAjaxApp.service('enrollments', ['$scope', '$http', EnrollmentService]);
Then, use the service anywhere else:
enrollmentService
.getEnrollments()
.then(function(enrollments) {
// You can use the data here.
console.log(enrollments);
});
The controller code
LoginService is service name you have to pass as a parameter to controller
var loginModule = angular.module('LoginModule',[]);
loginModule.controller('logincontroller', ['$rootScope','$scope','$http','$window','$cookieStore',
'LoginService',logincontrollerFun ]);
function logincontrollerFun($rootScope, $scope, $http, $window,$cookieStore, LoginService,RememberService) {
$scope.loginTest = function() {
LoginService.UserStatus($scope, function(resp) {
console.log("response of login controller ::: ", resp);
///write ur code
});
}
}
service code
var loginModule = angular.module('LoginModule')
loginModule.factory("LoginService",[ '$http', LoginServiceFun ])
function LoginServiceFun($http) {
function UserStatus($scope,callback){
var targetRequestPath='./url';
var targetRequestParamsREQ={'email':$scope.email,'password':$scope.passWord};
return $http({
method: 'POST',
url: targetRequestPath,
headers: {'Content-Type': 'application/json'},
data: targetRequestParamsREQ
}).then(function (response){
console.log('Response Data : ', response.data);
callback( response.data );
})
}
return {
UserStatus:UserStatus
}
}
In my angularJS application, I have set data received from one controller's ajax and put in factory method to reuse in other controllers. The problem is when user reload page, this factory method is useless.
app.factory('factory', function () {
return {
set: set,
get: get
}
});
app.controller ('testController', function ($scope, factory) {
if (factory.get('name')) {
$scope.name= factory.get('name');
} else {
$http.get(url).then(function(res) {
$scope.name= res.name;
factory.set('name', res.name);
});
}
});
What is the best way to retrieve this check in factory method which will get value from factory, if not there take from http service and in controller common code needs handle these two cases that done factory method?
Here when data taken from http service it returns promise otherwise plain value.
This code will fetch data from server if the 'cachedResult' variable is not set, otherwise return a promise from the stored variable.
app.factory('factoryName', ['$http','$q', function($http,$q) {
var cahedResult = null;
var myMethod = function(args) {
var deferred = $q.defer();
if (cahedResult){
deferred.resolve({ data : cahedResult });
return deferred.promise;
}
$http.get(....).then(function(response){
cahedResult = response.data;
deferred.resolve({ data : cahedResult });
},function(error){
deferred.reject('error');
});
}
};
return {
myMethod : myMethod
}
])
But you could also store the data in local storage or in a cookie when the first controller fetch the info so that it's available even if user refresh the browser.
First create a factory :
app.factory('factoryName', ['$http','$q', function($http,$q) {
return {
getData : function(arg1,arg2) {
return $http.get('/api-url'+arg1+'/'+arg2)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
return $q.reject(response.data);
});
}
}
}])
Provide every api details in this factory, so you can use this factory in multiple controllers.
In Controller inject the factory (factoryName) as a dependency.
app.controller ('testController',['$scope', 'factoryName', function($scope, factoryName) {
factoryName.getData(arg1,arg2,...)
.then(function(data) {
console.log(data);
}, function(error){
console.log(error);
});
}]);
For detailed description :- http://sauceio.com/index.php/2014/07/angularjs-data-models-http-vs-resource-vs-restangular/
Directly return a promise from your factory
app.factory('factoryName', function () {
var connectionurl ='...'; //Sample: http://localhost:59526/Services.svc
return {
connectionurl : connectionurl ,
methodName: function (parameters) {
$http({
method: 'GET',
url: connectionurl + 'servicemethod_name'
})}
}
}
});
In this case your controller will look like
app.controller ('testController', function ($scope, factoryName) {
factoryName.methodName(parameters).then(function(){
$scope.variable=response.data;
/*binding your result to scope object*/
}, function() {
/*what happens when error occurs**/
});
});
Other way is directly bind to a scope object through success callback function
app.factory('factoryName', function () {
var connectionurl ='...'; //Sample: http://localhost:59526/Services.svc
return {
connectionurl : connectionurl ,
methodName: function (parameters,successcallback) {
$http({
method: 'GET',
url: connectionurl + 'servicemethod_name'
}).success(function (data, status, headers, config) {
successcallback(data);
})
.error(function (data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}
}
});
In this case your controller will look like
app.controller ('testController', function ($scope, factoryName) {
factoryName.methodName(parameters,function(response){
/* your success actions*/
$scope.variable=response;
});
});
In the second case your error is handled in the factory itself. How ever you can also use errorcallback function.
I have a controller that is calling http.get, http.push and http.post methods.
I am learning angularjs and have found that it's best to call your http.get in your service file. I am able to do that with a simple http.get, but get confused with a http.get by id or http.get/http.post which takes a parameter:
My current controller looks like this
angular.module("app-complaints")
.controller("clcontrol", clcontrol);
function clcontrol($routeParams, $http, $scope) {
$http.get(baseURL + "/api/complaints/" + $scope.complaintCase + "/checklists")
.then(function (cl) {
//success
$scope.index = 0;
$scope.cl = [];
$scope.cl = cl;
}
I want to separate it out like this
controller.js
angular.module("app-complaints")
.controller('clcontrol', function ($http, $scope, $q, Service, $timeout) {
....
getCL();
function getCL(){
Service.getCl()
.success(function(cl){
$scope.cl = [];
$scope.cl = cl;
}
service.js
angular.module("app-complaints")
.factory('Service', ['$http', function ($http) {
Service.getCL = function () {
return $http.get(urlBase + "/api/complaints/" + complaintCase + "/checklists")
};
};
Simple. Make a factory that accepts parameters.
var app = angular.module("MyApp", [ /* dependencies */]);
app.factory("SharedServices", ["$http", function($http) {
return {
getItems: function(url, parameters) {
return $http.get(url, {
//optional query string like {userId: user.id} -> ?userId=value
params: parameters
});
},
postItem: function(url, item) {
var payload = {
item: item
};
return $http.post(url, payload);
},
deleteItem: function(url, item) {
var payload = {
item: item
};
return $http({
url: url,
data: payload,
method: 'DELETE',
});
}
// ETC. ETC. ETC.
// follow this pattern for methods like PUT, POST, anything you need
};
}]);
Use the service in your controller:
app.controller("MainCtrl", ["$scope","SharedServices", function($scope, SharedServices) {
//do things with the shared service
$scope.postMyThings = function() {
SharedServices.postItems('path/to/api', itemsArray).then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
};
$scope.getMyThing = function() {
SharedServices.getItems('path/to/api/get').then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
}
}]);
I am using a Angular factory, service and a controller. I use the service to $http get data from a url, send it to the factory who then handles the response data and sends a object to the controller:
Service:
module.exports = function($http, $q){
return {
getOptions: function () {
var deferred = $q.defer();
$http({ method: "GET", url: AppAPI.url + 'acf/v2/options/' })
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
}
};
Factory:
module.exports = function(optionsService){
var options = {};
var getOptions = optionsService.getOptions();
getOptions.then(function(items){
options = items;
});
return options;
};
Controller:
module.exports = function($scope, $http, optionsFactory){
console.log(optionsFactory);
};
But the Factory returns an empty options to the controller. How would you assign the items from the promise to the options object which get's returned to the controller?
UPDATE
Here is a fiddle
Would appreciate the help :)
Could you try changing
var getOptions = optionsService.getOptions();
// to
var getOptions = optionsService.getOptions;
If you created a plunkr/fiddle, that would help a bit.
I'm trying to use angular promise using $q that is wrapped in 'service' and call it from my controller.
Here is the code:
var myController = function ($scope, myService) {
$scope.doSomething = function (c, $event) {
$event.preventDefault();
myService.method1(c).then(function (rslt) {
alert(rslt);
}, function (err) {
alert(err);
}).then(function () {
//clean up
});
};
};
var myApp = angular.module('myApp', [])
.factory('myService', function($q) {
function _method1(c) {
var dfr = $q.defer();
var dt = { sc: c };
$.ajax({
type: "POST",
url: "mypage.aspx/mymethod",
data: JSON.stringify(dt),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
dfr.resolve('actions sucess');
},
error: function (msg) {
dfr.reject(msg);
}
});
return dfr.promise;
}
return { method1: _method1 };
}).controller('myController', myController);
The problem is that ' alert(rslt);' piece of code is never executed.
Service is called and data is updated but first 'then' function is not reached on first click.
What am I doing wrong?
Any help appreciated.
I would recoomend you to use $http and $resource instead of $.ajax
Heres an example of $http
myApp.factory('MyService',
[
'$http',
'$q',
'$resource',
function (
$http,
$q,
$resource
) {
return {
doSomething : function (somedata) {
var deferred = $q.defer();
$http({ method: 'POST', url: '"mypage.aspx/mymethod"', data: somedata }).
success(function (data, status, headers, config) {
deferred.resolve(true);
}).
error(function (data, status, headers, config) {
deferred.resolve(false);
});
return deferred.promise;
}
};
}]);
Just add the dependency to $rootScope and call $rootScope.$apply() in both callbacks from $.ajax():
success: function () {
dfr.resolve('actions sucess');
$rootScope.$apply();
}, ...
But better yet, use Angular's $http service.