Use services in angular js to get and set a variable - angularjs

I have a service function as show below
.service('ItemService', ['$http', function ($http) {
var items = [{'item_id': '1', 'item_name': 'abc'}];
return {
getItems: function () {
return items;
},
setItems: function (value) {
items = value;
}
};
}]);
This code is working fine, I want to make the items dynamic, For example
var items = $http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
method: 'POST',
url: 'http://localhost/app/item/get/10',
}).then(function (response) {
return response.data;
});
How should I do this ?

You service will be like this
.service('ItemService', ['$http', function($http) {
return {
getItems: function(id) {
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'GET',
url: 'http://localhost/app/item/get/' + id,
})
},
setItems: function(items) {
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
url: 'http://localhost/app/item/' + items,
})
}
};
}]);
And you should call it inside you controller like this
ItemService.getItems().then(function(response){
//Retrieve the data
$scope.items = response.items;
}, function(error){
//Handle the errors
})

.service('ItemService', ['$http', function ($http) {
// I want to initialize this items array before I call getItems funtion, Anyway to do the same?
var items = [{'item_id': '1', 'item_name': 'abc'}];
//Below section I want exactly same I will change items array from my controller and also I will use getItem again to get this items array agian. My getItems should only return the items array
return {
getItems: function () {
return items;
},
setItems: function (value) {
items = value;
}
};
}]);

Related

AngularJS scope variable undefined in page load for other function

Im trying to get initialize the scope variable via http get request in page load in first function but then when trying to use the scope variable in other function in the same page load, it is undefined.
app.controller('GradeAndSectionCtrl', function ($scope, $http) {
$scope.GetCategories = function () {
$http({
method: 'GET',
url: '/GradeAndSection/GetCategories'
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
}
});
};
$scope.GetGrades = function () {
\\$scope.drpCategory; here; is; undefined;
$http({
method: 'GET',
url: '/GradeAndSection/GetGrades?categoryID=' + $scope.drpCategory
}).then(function (response) {
$scope.grades = response.data;
});
};
$scope.GetCategories();
$scope.GetGrades();
});
You are making asynchronous call using promises in your code therefore $scope.drpCategory may not be loaded when you call GetGrades function. You can call your GetGrades function when GetCategories is resolved.
$scope.GetCategories = function () {
$http({
method: "GET",
url: "/GradeAndSection/GetCategories"
}).then(function (response) {
$scope.categories = response.data;
if (response.data != null) {
$scope.drpCategory = $scope.categories[0].categoryID;
$scope.GetGrades();
}
});
}
Try to call the function GetGrades in then()
$scope.GetCategories = () => {
$http
({
method: 'GET',
url: 'categories.json',
})
.then(data => {
$scope.categories = data.data;
$scope.drpCategory = $scope.categories[0].category
$scope.GetGrades($scope.drpCategory)
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
}
$scope.GetGrades = (drpCategory) => {
$http
({
method: "GET",
url: "categories_" + drpCategory + ".json"
}).then(function (response) {
$scope.grades = response.data;
console.log($scope.grades)
});
}
$scope.GetCategories()
Working example: http://plnkr.co/edit/ZN8nI7OhAyWiJWlqeJsU?p=preview

Angular $http Respose Data is Undefined

I am trying to access an xml file from the server.
When I check in using code inspector the value of response.data is all set.
But the returned data is not reaching the controller.
In the controller. response.data is undefined.
fuseApp.factory('fuseHttpRequest', ['$http', function ($http) {
var getRequest = function () {
var xml;
xml = $http({
method: 'GET',
url: 'http://vlandproperties.com/apitest/orders.xml',
headers: {
'Content-Type': 'application/xml'
},
timeout: 10000,
transformResponse: function (data) {
return data;
}
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
return response.data
});
};
return {
getRequest: getRequest
};
}]);
console.log output

why i get $$State variable with a service angularjs

i want to get just my service in the variable from my controller but it give me an $$state object
this is my controller
$scope.myDataSMS = ServiceSms.async().then(function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
});
console.log($scope.myDataSMS);
and my service
routeAppControllers.factory('ServiceSms', function($http,Token) {
var key = Token.CreateToken()
var myService = {
async: function() {
var data = 'token=' + encodeURIComponent(key);
var promise = $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data) {
// The then function here is an opportunity to modify the response
// console.log(data.data);
// The return value gets picked up by the then in the controller.
return data.data;
})
// Return the promise to the controller
return promise;
}
};
return myService;
});
i think that the problems is with the promise but there i m little bit stuck
if someone can help me please
thanks in advance
this would be a better way to write your promise:
CONTROLLER:
.controller('nameofcontroller', ['$scope', 'ServiceSms', function($scope, ServiceSms) {
$scope.myDataSMS = ServiceSms.async()
.then(
function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
},
function(err){
console.log('err: ' + err);
});
}]);
SERVICE:
routeAppControllers.factory('ServiceSms', function($http,Token) {
return {
async: function() {
var data = 'token=' + encodeURIComponent(key);
return $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
});

chrome shows the error TypeError: Cannot read property 'then' of undefined, even the promise was returned?

i have the following code for save operation:
here is my angular service: this already returns the promise
factory('customersaveService', function ($http, $q) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
var deffered = $q.defer();
$http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
.success(function (d) {
deffered.resolve(d);
})
.error(function (e) {
deffered.reject(e);
});
}
return factoryObject;
});
in here the promise is returned. therefore it shoudl not throw the error
"TypeError: Cannot read property 'then' of undefined"
the error comes from the controller's code:
$scope.SaveCustomer = function (data)
{
if ($scope.ButtonText == 'Save')
{
$scope.message = "";
$scope.submitted = true;
$scope.User = data;
console.log($scope.User);
customersaveService.SaveNewUserSrv($scope.User).then(function (d) { <=== error line
console.log('before success part');
if (d == 'success')
{
console.log('im in success part');
clearform();
}
},
function (e) {
});
}
}
why this throws the error when the promise was returned?
1.Create service like below :
2.No need of $q service.
factory('customersaveService', function ($http) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
}
return factoryObject;
});
factory('customersaveService', function ($http) {
var SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: { 'cust': data }
});
};
return {
SaveNewUserSrv: SaveNewUserSrv
};
});
And in the controller, sure you inject the service customersaveService

How to return data from Factory Angular?

How to return data from factory?
.factory('albumService', ['$http', function($http) {
return {
getAlbums: function (type) {
var request = $http({
method: "POST",
url: "/albums/getalbums",
data: $.param({ type : type }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
request.success(function (data) {
return data;
});
}
};
}])
I need return data from factory in section
request.success(function (data) {
return data;
});
That result will be in $scope.albums = albumService.getAlbums('select');
Service :
.factory('albumService', ['$http', '$q, function($http,$q) {
return {
getAlbums: function (type) {
var albumPromise = $q.defer();
$http({
method: "POST",
url: "/albums/getalbums",
data: {'type':type},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data){
return albumPromise.resolve(data);
})
.error(function(error){
return albumPromise.reject(error);
})
return albumPromise.promise;
}
};
}])
Inside yr Controller call it like this.
albumService.getAlbums('select')
.then(function(data){
$scope.albums=data;
}, function(error){
console.log('failed'+error);
})

Resources