AngularJS binding service variable to controller - angularjs

I am a Angular noob and having problems with binding a variable from one of my services to one of my controllers. I have read at least a dozen posts on the subject and nothing seems to be working for me.
Here is the controller:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
$scope.selectedTeam = teamService.getTeam(teamId, $scope.login.loginId);
};
}]);
Here is the service:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
this.selectedTeam = data.response;
return data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
return {};
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
And here is the template:
<div class="jumbotron main-jumbo" ng-controller="TeamController">
<h1>{{selectedTeam.teamName}}</h1>
</div>
I have tried binding to the getSelectedTeam function and the service variable itself. Do I need to set up a $watch function in the controller? Any assistance would be greatly appreciated.
EDIT:
I tried turning my service into a factory, which still did not help me, so then I looked at a provider that was properly working that I had already written in the application. I converted my "teamService" into a provider and finally worked like a charm. Thanks for the contributions guys.
Code from my new provider:
angular.module('teamService', [])
.provider('teamService', function () {
var errorState = 'error',
logoutState = 'home';
this.$get = function ($rootScope, $http, $q, $state) {
/**
* Low-level, private functions.
*/
/**
* High level, public methods
*/
var wrappedService = {
/**
* Public properties
*/
selectedTeam: {teamName:"Select a team"},
userTeams : null,
createTeam: function(loginId, name, description, locationName, managed){
var postData = {loginId:loginId, teamName:name, teamDescription:description, teamLocationName:locationName, teamManaged:managed};
var promise = $http({
url: "/create-team-url",
method: "POST",
data: postData
});
return promise;
},
getTeam: function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/get-team-url",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
wrappedService.selectedTeam = data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
wrappedService.selectedTeam = {};
});
},
getUserTeams: function(loginId) {
var postData = {loginId: loginId};
var promise = $http({
url: "/team-list-url",
method: "POST",
data: postData
});
return promise;
},
joinTeam: function(teamId, loginId){
var postData = {teamId:teamId, loginId:loginId};
var promise =$http({
url: "/join-team-url",
method: "POST",
data: postData
});
return promise;
},
getSelectedTeam: function(){
return wrappedService.selectedTeam;
}
};
return wrappedService;
};
});

As seen in my edit. I converted my service into a provider and all the changes seem to propagate to the view with no issues. I need to further analyze the difference between the factory, service, and provider in order to gain a higher understanding of what is going on here.

The main issue with the code is the way that promises are used. You can either correct that within the service, or handle it in the controller. As an example of the latter, you can re-write the above as:
Controller Code:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
teamService.getTeam(teamId, $scope.login.loginId).then(
function(result){
$scope.selectedTeam = result.data;
},
function(error){
console.log(error);
}
)
};
}]);
Service code:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
return $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
You can also handle this in the service itself, but it requires a little more code. The key thing is that the getTeam call is asynchronous and needs to be handled using proper promise constructs.

Related

$http.post in angularJS goes in error in without debugging mode only.in debugging mode its works fine.why?

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.

How to set a variable from an $http call then use it in the rest of the application WITHOUT making the whole application asynchronous

I have this data
{
"config": {
"RESTAPIURL": "http://myserver/myrestsite"
}
}
and I have this factory that reads that data
'use strict';
angular.module('myApp').factory('api',
["$http", "$q",
function ($http, $q) {
function _getConfiguration() {
var deferred = $q.defer();
$http.get('/scripts/constants/config.json')
.success(function (data) {
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject(data, status);
});
return deferred.promise;
}
function _restApiUrl() {
// this doesn't work either. _getConfiguration() doesn't resolve here.
return _getConfiguration().RESTAPIURL + '/api/';
}
return {
URL: _restApiUrl
}
}
]
);
Then to use it
'use strict';
angular.module('myApp').factory('AuthService', function ($http, $q, api,NotificationService) {
function _get(creds) {
var deferred = $q.defer();
$http({method: 'GET', url: api.URL() + api.AUTH, headers: {
'Authorization': 'Basic '+creds}
})
.success(function (data, status, results, headers) {
deferred.resolve(results);
})
.error(function (data, status) {
NotificationService.redirect(status);
deferred.reject(data, status);
});
return deferred.promise;
}
return {
get:_get
};
});
So when I'm using it I am doing api.URL() and it's not working.
It used to be hard coded URL so to call it used to be api.URL. I really don't want to go through the whole app and convert everything to api.URL().then(...). That would suck.
So how can I nail down this value as a "property" instead of an asynchronous promise that has to be called over and over?
Call it once, fine. Get the value. Put it somewhere. Use the value. Don't ever call the $http again after that.
EDIT
This is turning up to be one of the most successful questions I've ever asked, and I am gratefully going through each answer in turn. Thank each one of you.
Adding a bit to what #ThinkingMedia was saying in the comment, with ui-router when defining controllers you can add a resolve parameter.
In it you can specify some promises that have to resolve before the controller is instantiated, thus you are always sure that the config object is available to the controller or other services that the controller is using.
You can also have parent/child controllers in ui-router so you could have a RootController that resolves the config object and all other controllers inheriting from RootController
.state('root', {
abstract: true,
template: '<ui-view></ui-view>',
controller: 'RootController',
resolve:{
config: ['api', function(api){
return api.initialize();
}
}
});
and your api factory:
angular.module('myApp').factory('api',
["$http", "$q",
function ($http, $q) {
var _configObject = null;
function initialize() {
return $http.get('/scripts/constants/config.json')
.then(function (data) {
_configObject = data;
return data;
});
}
// you can call this in other services to get the config object. No need to initialize again
function getConfig() {
return _configObject;
}
return {
initialize: initialize,
getConfig: getConfig
}
}
]
);
I would pass a callback to the getURL method, and save the URL when it returns. Then I would attach any subsequent requests to that callback. Here I am assuming that you are doing something similar with api.AUTH that you don't have a reference to in your code.
Pass a callback to the getURL method in the api service.
angular.module('myApp').factory('api', ["$http", "$q",
function ($http, $q) {
function _getConfiguration() {
var deferred = $q.defer();
$http.get('/scripts/constants/config.json')
.success(function (data) {
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject(data, status);
});
return deferred.promise;
}
return {
getURL: function (cb) {
var that = this;
if (that.URL) {
return cb(that.URL);
}
_.getConfiguration().then(function (data) {
that.URL = data.config.RESTAPIURL + "/api";
cb(that.URL);
});
}
}
}]);
And in your AuthService, wrap your _get inside a callback like this:
angular.module('myApp').factory('AuthService', function ($http, $q, api, NotificationService) {
function _get(creds) {
var deferred = $q.defer();
var getCallback = function (url) {
$http({
method: 'GET',
url: url + api.AUTH,
headers: {
'Authorization': 'Basic ' + creds
}
})
.success(function (data, status, results, headers) {
deferred.resolve(results);
})
.error(function (data, status) {
NotificationService.redirect(status);
deferred.reject(data, status);
});
};
api.getURL(getCallback);
return deferred.promise;
}
return {
get: _get
};
});
Why don't you initialize the factory when the app is loading and put the variable onto another property? Something like this:
angular.module('myApp').factory('api', ["$http", "$q",
function ($http, $q) {
// store URL in a variable within the factory
var _URL;
function _initFactory() {
var deferred = $q.defer();
$http.get('/scripts/constants/config.json')
.success(function (data) {
// Set your variable after the data is received
_URL = data.RESTAPIURL;
deferred.resolve(data);
});
return deferred.promise;
}
function getURL() {
return _URL;
}
return {
initFactory: _initFactory,
URL: getURL
}
}
]
);
// While the app is initializing a main controller, or w/e you may do, run initFactory
//...
api.initFactory().then(
// may not need to do this if the URL isn't used during other initialization
)
//...
// then to use the variable later
function _get(creds) {
var deferred = $q.defer();
$http({method: 'GET', url: api.URL + api.AUTH, headers: {
'Authorization': 'Basic '+creds}
})
.success(function (data, status, results, headers) {
deferred.resolve(results);
})
return deferred.promise;
}
I see you haven't used any $resource's here, but I'm hoping you have a good understanding of them:
in factories/delay-resource.js:
'use strict'
angular.module('myApp').factory('delayResource', ['$resource', '$q',
function($resource, $q){
var _methods = ['query', 'get', 'delete', 'remove', 'save'];
var shallowClearAndCopy = function(src, dst) {
dst = dst || {};
angular.forEach(dst, function(value, key){
delete dst[key];
});
for (var key in src) {
if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
return dst;
}
var delayResourceFactory = function(baseUrlPromise, url, paramDefaults){
var _baseUrlPromise = baseUrlPromise,
_url = url,
_paramDefaults = paramDefaults;
var DelayResource = function(value){
shallowClearAndCopy(value || {}, this);
};
_methods.forEach(function(method){
DelayResource[method] = function(params, successCB, errCB, progressCB){
if (angular.isFunction(params)) {
progressCB = successCB;
errCB = errHandlers;
successCB = params;
errHandlers = params = null;
}
else if (!params || angular.isFunction(params)){
progressCB = errCB;
errCB = successCB;
successCB = errHandlers;
params = {};
}
var _makeResultResource = function(url){
var promise = $resource(url, _paramDefaults)[method](params);
(promise.$promise || promise).then(
function successHandler(){
var data = arguments[0];
if (isInstance){
if (angular.isArray(data))
for (var i = 0; i < data.length; i++)
data[i] = new DelayResource(data[i])
else if (angular.isObject(data))
data = new DelayResource(data)
}
successCB.apply(successCB, arguments)
resultDelay.resolve.apply(resultDelay.resolve, arguments)
},
function(err){
errCB.apply(errCB, arguments)
resultDelay.reject.apply(resultDelay.reject, args)
},
function(){
progressCB.apply(progressCB, arguments)
resultDelay.notify.apply(resultDelay.notify, arguments)
}
)
}
var isInstance = this instanceof DelayResource,
resultDelay = $q.defer();
if (!angular.isString(_baseUrlPromise) && angular.isFunction(_baseUrlPromise.then))
_baseUrlPromise.then(
function successCb(apiObj){
_makeResultResource(apiObj.RESTAPIURL + _url)
},
function successCb(){
throw 'ERROR - ' + JSON.stringify(arguments, null, 4)
})
else
_makeResultResource(_baseUrlPromise.RESTAPIURL + _url);
return resultDelay.promise;
};
DelayResource.prototype['$' + method] = function(){
var value = DelayResource[method].apply(DelayResource[method], arguments);
return value.$promise || value;
}
});
return DelayResource;
}
return delayResourceFactory;
}]);
This will be the base factory that all requests to that REST API server will go through.
Then we need a factories/api-resource.js:
angular.module('myApp').factory('apiResource', ['delayResource', 'api', function (delayResource, api) {
return function (url, params) {
return delayResource(api.URL(), url, params);
};
}])
Now all factories created will just have to call the apiResource to get a handle on a resource that will communicate with the REST API
Then in a file like factories/account-factory.js
angular.module('myApp').factory('AuthRoute', ['apiResource', 'api', function (apiResource, api) {
return apiResource(api.AUTH);
}]);
Now in factories/auth-service.js:
'use strict';
angular.module('myApp').factory('AuthService', ['$q', 'AuthRoute', 'NotificationService', function ($q, AuthRoute, api, NotificationService) {
function _get(creds) {
var deferred = $q.defer();
AuthRoute.get()
.then(
function successCb(results){
deferred.resolve(results);
},
function errCb(){
// cant remember what comes into this function
// but handle your error appropriately here
//NotificationService.redirect(status);
//deferred.reject(data, status);
}
);
return deferred.promise;
}
return {
get:_get
};
}]);
As you can imagine, I haven't been able to test it yet, but this is the basis. I'm going to try create a scenario that will allow me to test this. In the mean time, feel free to ask questions or point out mistakes made
Late Addition
Forgot to add this:
'use strict';
angular.module('myApp').factory('api', ["$http", "$q", function ($http, $q) {
var restApiObj,
promise;
function _getConfiguration() {
if (restApiObj)
return restApiObj;
if (promise)
return promise;
promise = $http.get('/scripts/constants/config.json')
.then(function (data) {
restApiObj = data;
promise = null;
return data;
},
function (data, status) {
restApiObj = null;
promise = null;
});
return promise;
}
return {
URL: _getConfiguration
}
}]);
Continuing with the ui-router scenario
.state('member-list', {
url: '/members?limit=&skip='
templateUrl: '/views/members/list.html',
controller: 'MemberListCtrl',
resolve:{
members: ['$stateParams', 'MembersLoader', function($stateParams,MembersLoader){
return MembersLoader({skip: $stateParams.skip || 0, limit: $stateParams.limit || 10});
}
}
});
factory
.factory('MemberRoute', ['apiResource', function(apiResource){
return apiResource('/members/:id', { id: '#id' });
}])
.factory('MembersLoader', ['MembersRoute', function(MembersRoute){
return function(params){
return MemberRoute.query(params);
};
}])
.factory('MemberFollowRoute', ['apiResource', 'api', function(apiResource, api){
return apiResource(api.FOLLOW_MEMBER, { id: '#id' });
}])
controller
.controller('MemberListCtrl', ['$scope', 'members', 'MemberRoute', 'MemberFollowRoute', function($scope, members, MemberRoute, MemberFollowRoute){
$scope.members = members;
$scope.followMember = function(memberId){
MemberFollowRoute.save(
{ id: memberId },
function successCb(){
//Handle your success, possibly with notificationService
},
function errCb(){
// error, something happened that doesn't allow you to follow memberId
//handle this, possibly with notificationService
}
)
};
$scope.unfollowMember = function(memberId){
MemberFollowRoute.delete(
{ id: memberId },
function successCb(){
//Handle your success, possibly with notificationService
},
function errCb(){
// error, something happened that doesn't allow you to unfollow memberId
//handle this, possibly with notificationService
}
)
};
}]);
With all this code above, you will never need to do any sort of initialization on app start, or in some abstract root state. If you were to destroy your API config every 5 mins, there would be no need to manually re-initialize that object and hope that something isn't busy or in need of it while you fetch the config again.
Also, if you look at MembersRoute factory, the apiResource abstracts/obscures the api.URL() that you were hoping not to have to change everywhere. So now, you just provide the url that you want to make your request to, (eg: /members/:id or api.AUTH) and never have to worry about api.URL() again :)

Angular Js : undefined value in pop up

I get a problem in AngularJS when getting data from JSON using service factory ($resource)
services.factory('GetCustomerByEmailFactory', function ($resource) {
return $resource(url + '/customerService/getCustomerByMail?email=:email', {}, {
getByMail: { method: 'GET', params: {email: '#email'} }
});
});
this service works well
but the controller part doesn't work
app.controller('CustomerCreationCtrl', ['$scope','PostCustomerFactory', '$location','Subscription','AddNotificationFactory','$routeParams','GetCustomerByEmailFactory',
function ($scope, PostCustomerFactory, $location,Subscription,AddNotificationFactory,$routeParams,GetCustomerByEmailFactory) {
$scope.customer ={};
$scope.not ={};
$scope.aftercustomer ={};
$scope.createNewCustomer = function(){
Number($scope.customer.PhoneNumber);
$scope.customer.SubscriptionDate = "1990-02-23T00:00:00";
$scope.customer.ManagerIdCustomer=1;
PostCustomerFactory.create($scope.customer);
var customer = GetCustomerByEmailFactory.getByMail({email:$scope.customer.Email}).$promise;
customer.then(function (responce){
$scope.aftercustomer = responce;
window.alert($scope.aftercustomer.Id);
$scope.not.CustomerId = $scope.aftercustomer.Id;
$scope.not.ManagerId = $routeParams.id;
AddNotificationFactory.create($scope.not);
});
$location.path("/login");
};
}]);
the window.alert show me an undefined value so that it doesn't get the data

Using a factory with $http promise returns empty object

I have this simple factory that fetches a data file and saves it to service.data:
angular.module("tiki").factory("editTiki", ["$http", function($http){
var service = {}
service.data = {}
service.getTikis = function(){
$http.get("data/tikis.json").success(function(tikis){
console.log(tikis)
service.data = tikis
})
}
return service
}])
Then, in the controller i assign it to the $scope. This is first empty ofcourse but when the $http resolves it should update my factory and in turn update the service.data object with the returned data.
angular.module('tiki').controller("tiki.controller.settings.edit", ["$scope", "editTiki", function($scope, editTiki){
//should return the tikis
$scope.preview = editTiki.data
editTiki.getTikis()
$scope.showEditTikiObject = function(){
console.log($scope.preview)
}
}])
However, i have this function to test the contents of the data and it returns an empty object. Why is that?
You are reassigning service.data = tikis after assigning it to $scope.preview.
You should do probably something with the promise.
angular.module("tiki").factory("editTiki", ["$http", function($http){
var service = {};
service.data = {};
service.getTikis = function(){
return $http.get("data/tikis.json").success(function(tikis){
console.log(tikis)
service.data = tikis;
return service.data;
})
};
return service;
}]);
angular.module('tiki').controller("tiki.controller.settings.edit", ["$scope", "editTiki", function($scope, editTiki){
editTiki.getTikis()
.then(function () {
$scope.preview = editTiki.data;
});
$scope.showEditTikiObject = function(){
console.log($scope.preview);
};
}])
I ended up with the following. So here I am not injecting the scope object into the factory, but setting the $scope in the controller itself using the concept of promise returned by $http service. Hope this helps.
(function () {
getDataFactory = function ($http)
{
return {
callWebApi: function (reqData)
{
var dataTemp = {
Page: 1, Take: 10,
PropName: 'Id', SortOrder: 'Asc'
};
return $http({
method: 'GET',
url: '/api/PatientCategoryApi/PatCat',
params: dataTemp, // Parameters to pass to external service
headers: { 'Content-Type': 'application/Json' }
})
}
}
}
patientCategoryController = function ($scope, getDataFactory) {
alert('Hare');
var promise = getDataFactory.callWebApi('someDataToPass');
promise.then(
function successCallback(response) {
alert(JSON.stringify(response.data));
// Set this response data to scope to use it in UI
$scope.gridOptions.data = response.data.Collection;
}, function errorCallback(response) {
alert('Some problem while fetching data!!');
});
}
patientCategoryController.$inject = ['$scope', 'getDataFactory'];
getDataFactory.$inject = ['$http'];
angular.module('demoApp', []);
angular.module('demoApp').controller('patientCategoryController', patientCategoryController);
angular.module('demoApp').factory('getDataFactory', getDataFactory);
}());

How can I move HTTP requests out of an AngularJS controller and into a service?

I have the following code snippet:
angular.module('test', []).controller('TestCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
params: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
}
It was suggested to me that I should maybe consider creating service(s) for $http requests
Can someone give me an example of how I could do this for the code above. In particular I am not sure how to set up the service and make the controller inject it.
Your service needs to look something like this:
angular.module('testaccount', []).
factory('TestAccount', function($http) {
var TestAccount = {};
TestAccount.get = function(applicationId, callback) {
$http.get('/Admin/GetTestAccounts?applicationId=' + applicationId).success(function(data) {
callback(data);
});
};
return TestAccount;
});
Your controller needs to inject the service, call the service object with the parameter, and send in a callback function:
angular.module('test', ['testaccount']).controller('TestCtrl', function ($scope, TestAccount) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
TestAccount.get(3, function (data) {
$scope.testAccounts = data;
})
}
Read more about service dependency injection in the tutorial.

Resources