I have a new userService that is working fine, but I would like to initialize certain vars only when a new user starts up the site.
For example, I would like ONLY fetch the user's unique session ID just once, and access that ID from any controller. My understanding is that I'll init the sessionID vars once in my service, then each time I call the service I will NOT need to make the http call again.
Would app.js serve my purposes in this case ? Again, I need to sessionID available to every controller WITHOUT the need to make an http call each time (i.e. caching the sessionID in some way).
Here's my current app.js for example :
(function () {
'use strict';
var app = angular.module('app', [
// Angular modules
'ngAnimate',
'ngRoute',
'ngSanitize',
// Custom modules
'common', // common functions, logger, spinner
'common.bootstrap', // bootstrap dialog wrapper functions
// 3rd Party Modules
'ui.bootstrap', // ui-bootstrap (ex: carousel, pagination, dialog)
'kendo.directives', // Kendo UI
'app.customcontrollers' // Language/Currency settings
]);
app.run(['$route', function ($route) {
// Include $route to kick start the router.
}]);
})();
And my userService (this.openUserSession pulls the sessionID) :
(function () {
'use strict';
var app = angular.module('app');
app.service('userService', ['$http', 'common', userService] );
function userService($http, common){
// define private vars
var _rzEnvParams = [];
var _sessionID = '';
var _rzInitStatus = '';
var _domain = '';
var _port = '' ;
var _controllerpath = '';
var _space = '';
var _env = '';
var _clariteconfig = '';
var $q = common.$q;
this.initRz = function (rzEnvParams) {
// some lines of code omitted for brevity...
var url = ... ;
var deferred = $q.defer();
deferred.notify("Getting Rage init parameters...");
var retval = [];
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
retval = data;
deferred.resolve(retval);
});
return deferred.promise;
}
this.openUserSession = function(domain, port, controllerpath, user, pass) {
domain = "localhost:"
port = "49479";
controllerpath = "/api/open";
user = "";
pass = "";
var url = "http://" + domain + port + controllerpath + "?userid=" + user + "&pass=" + pass;
var deferred = $q.defer();
deferred.notify("Opening user session...");
var retval = [];
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
retval = data;
deferred.resolve(retval);
});
return deferred.promise;
}
}
})();
I currently call openUserSession() from my dashboard.js as follows :
userService.openUserSession().then(function (data) {
response = data[0].split(",")
status = response[0];
vm.sessionID = response[1].split('"')[1];
});
but wouldn't I need to somehow session sessionID within userService so it becomes available in cache ?
thanks in advance.
Bob
Related
here is my AngularJs code
<script>
var app = angular.module('myApp', []);
app.controller('employeeController', function($scope, $http) {
$scope.myFunction = function() {
// $scope.employees = response.userList;
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
method : "POST",
url : "loaduser",
headers: { 'Content-Type': 'application/json' },
data: {application: app, from: d1, to: d2}
}).success(function (response) {
$scope.firstName = response.estate;
$scope.employees = response.estate;
//console.log($scope.employees+" ::: "+JSON.stringify($scope.employees));
});
}
}
)
.config(function($httpProvider){
$httpProvider.defaults.withCredentials = true;
})
;
In the above code I have tried to get request in filter but I'm unable to get cookie saved in browser from that request
In your server side response header should contain below settings:
Access-Control-Allow-Origin: http://your-client-side-url
Access-Control-Allow-Credentials: true
here is my javascript code
$scope.addUser = function () {
debugger;
url = baseURL + "AddUser";
$scope.objUser = [];
$scope.objUser.push( {
"ID": '0',
"UserName": $scope.txtUserName,
"Password": $scope.txtPassword,
"Role":"Non-Admin"
});
$http.post(url,$scope.objUser[0])
.success(function (data) {
debugger;
alert("S");
window.location = "../View/Login.html";
}).error(function () {
debugger;
alert("e");
});
}
here is my server method code
[HttpPost]
public int AddUser(UserModel user)
{
//_entity.Configuration.ProxyCreationEnabled = false;
tblUser objUser = new tblUser();
objUser.UserName = user.UserName;
objUser.Password = user.Password;
objUser.Role = user.Role;
_entity.tblUsers.Add(objUser);
_entity.SaveChanges();
return objUser.ID;
}
You can use promises to get the response. this can be inside into a service and call it whenever you want to use it.
this.addUser = function (obj) {
var datosRecu = null;
var deferred = $q.defer();
var uri = baseUrl + 'addUser';
$http({
url: uri,
method: 'post',
data: angular.toJson(obj)
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
return deferred.promise;
};
Also .error and .success are deprecated.
PD: the parameter data: inside the $http correspond to the body. if you want to send parameters you should use params:{}
EDIT:
Here i leave you a link how promises work. Angular promises
Basically this helps to process data asynchronously
the example above can be used inside a service like this
myApp.service('myService', function($q, $http){
// here your services....
});
the service can be injected inside to any controller to provide the data that what you want, inside of your functions
myApp.controller('myController', function($scope, myService){
$scope.list = function(){
$promise = myService.getAll(); // this will be the name of your function inside your servive
$promise.then(function(data){
console.log(data); //here you can se your promise with data like status and messages from the server.
});
};
});
Hope it helps.
I'm having trouble with callbacks and asynchronous requests in angular. I created a service to fetch the data which uses callbacks (once the calls_left hits 0, callback is called). I inject my service inside my controller and then call the getMInterval on my service (metr.getMInterval) which should initialize the data (pTypes in this case) and wait till it is finished. The problem is that pTypes logs first as empty Array []. Any ideas?
Service:
angular.module('mService', ['config']).service('metr', function($http, $window, $rootScope, $location, config) {
var pTypes = [];
var intervalData = {};
function fetchMInterval(callback) {
var calls_left = 1;
var onComplete = function() {
calls_left--;
if (calls_left == 0) {
console.log("finished retrieving data from api");
if (callback) callback();
}
};
var url = 'fetch_data_from_this_url';
$http({
method: 'GET',
url: url
}).then(function success(response) {
console.log(response);
var data = JSON.parse(response.data.split(config.DELIMITER)[1]);
intervalData = data["Data"];
pTypes = metrIntervalData["pTypes"];
onComplete();
}, function error(response) {
alert("Failed to fetch info from " + url + "! " + response.status);
onComplete();
});
}
return {
getMInterval:function() {return fetchMInterval();},
getPTypes:function() {return pTypes;},
}
Controller:
app.controller('mController', function($scope, $filter, metr, config) {
metr.getMInterval();
$scope.pTypes = metr.pTypes();
console.log(metr.pTypes()); //console logs Array []
});
I try to make a unit test on that code that consists of factory that take behavior Name and contracts an http request in a closure ?
var app = angular.module("behaviour",[]);
var behaviour = app.factory('Behaviours',['http',function(http){
var BehavioursJson = $http.get('data.json');
return {
getBehaviour : function(behaviourName) {
if (BehavioursJson[behaviourName]) {
var behaviour = BehavioursJson[behaviourName];
return function (behaviourData, callback) {
var keys = Object.allKeys(behaviourData);
var headers = {};
var data = {};
var url = behaviour.path;
// some process to fill headers and data objects
$http({
method: behaviour.method,
url: url,
data: data,
headers: headers
}).then(function successCallback(response) {
callback(response,null);
},function errorCallback(error) {
callback(null,error);
});
}
};
return null;
}
}
}]);
Note: using jasmine
I will try below logic, but its not working.
In Angular JS:
$scope.Save = function () {
var items = $scope.invoice.items;
var obj = [{ sMemberCode: 'ALMA0502' }];
var request = $http({
method: "post",
url: sServiceURL + 'SaveData',
data: obj
});
};
In WCF Service :
[OperationContract]
[WebInvoke(UriTemplate = "SaveData",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST")]
bool SaveData(WcfService1.Common obj);
please tell me what I am wrong...
Try this
this.post = function (ItemDetails) {
$http.post('http://localhost:4191/Service1.svc/addItemMaster', ItemDetails).
success(function (data) {
console.log('data', data);
// when call is successful you code here
}).
error(function (err){
console.log('Error:', err);
});
};
Did you inject $http service in your controller?
Something like this:
var app = angular.module('youAppModule', []);
app.controller('controllerName',['$http', function($http){
// the above code in here
}]);