$scope is not updated after database trigger - angularjs

I have following controller which is posting a new user and also getting new users.
The problem here is after adding a new user, the scope is not updated so view is not affected. I have also tired returning the function so it expects a promise but didnt update the scope.
myapp.controllers('users', ['usersService', ''$scope',', function(usersService, $scope){
getUsers();
function getUsers(params) {
if (typeof(params) === "undefined") {
params = {page: 1};
}
usersService.getUsers(params).then(function (res) {
$scope.users = res.items;
$scope.usersListTotalItems = res._meta.totalCount;
$scope.usersListCurrentPage = res._meta.currentPage + 1;
});
}
}
$scope.addUser = function (user) {
usersService.adddNewUser(user).then(function (response) {
getUsers();
});
}
}]);
myApp.factory('userService', ['Restangular', '$http', function (Restangular, $http) {
return {
getUsers: function (params) {
var resource = 'users/';
var users = Restangular.all(resource);
return users.getList(params)
.then(function (response) {
return {
items : response.data[0].items,
_meta : response.data[0]._meta
}
});
},
adddNewUser: function (items) {
var resource = Restangular.all('users');
var data_encoded = $.param(items);
return resource.post(data_encoded, {}, {'Content-Type': 'application/x-www-form-urlencoded'}).
then(function (response) {
return response;
},
function (response) {
response.err = true;
return response;
});
}
};
}]);

I think it is a small error however you did not include $scope in the argument for the controller function.
myapp.controllers('users', ['usersService','$scope', function(usersService $scope){
getUsers();
function getUsers(params) {
if (typeof(params) === "undefined") {
params = {page: 1};
}
usersService.getUsers(params).then(function (res) {
$scope.users = res.items;
$scope.usersListTotalItems = res._meta.totalCount;
$scope.usersListCurrentPage = res._meta.currentPage + 1;
});
}
}
$scope.addUser = function (user) {
usersService.adddNewUser(user).then(function (response) {
getUsers();
});
}
}]);

Related

AngularJS 1.7 - HTTP POST

Upgrade to angularjs version 1.7 and this code does not compile
app.factory('LoginService', function ($http) {
return {
login: function (param, callback) {
$http.post(url, param)
.success(callback)
.error(function (data, status, headers, config) {
});
}
};
});
On the controller I make the call to the service LoginService
function LoginController($http, $location, LoginService, blockUI) {
var vm = this;
LoginService.usuario(
{login: vm.username, clave: vm.password},
function (data, status, headers, config) {
vm.resultado = data;
if (vm.resultado == "True") {
window.location = "/Home/Index";
} else {
vm.error = 'Usuario o password incorrecto';
}
});
};
I want to know how the function is called from the controller because it implemented the http.post service using .then
app.factory('LoginService', function ($http) {
return {
login: function (data) {
$http.post(url, data)
.then(function (resultado) {
debugger;
if (resultado.data === "True") {
return resultado.data;}
else {
console.log("NO");}
});
}};
});
I suggest you get familiar with a AngularJS $q service and its Promise API.
You LoginService.login(...) method should return the Promise from $http.post(...):
app.factory('LoginService', function ($http) {
return {
login: function (data) {
return $http.post(url, data)
.then(function(response) {
return response.data;
});
});
Then, your Controller can access the returned data via the resolved Promise:
function LoginController(LoginService) {
var vm = this;
LoginService.login({login: vm.username, clave: vm.password})
.then(function (result) {
// handle result here...
});
the solution would be this:
function LoginController($scope,$window,$q,LoginService) {
$scope.fnBusqueda = function () {
var promesas = [
obtenerLogin()
];
$q.all(promesas).then(function (promesasRes) {
var oArrayResponse = promesasRes;
if ((oArrayResponse.length > 0)) {
$scope.respuesta = oArrayResponse[0];
if ($scope.respuesta == "True") {
window.location = "/Home/Index";
} else {
$cope.error = 'Usuario o password incorrecto';
}
}
});
};
function obtenerLogin() {
var defered = $q.defer();
var promise = defered.promise;
LoginService.login(url_valida_login, '{login:X,clave:X}').then(function (response) {
defered.resolve(response);
}).catch(function (data) {
defered.resolve([]);
})
return promise;
}
}

Angular Js - Why I am getting Undefiend in controller while I am getting data from service?

I have made a service and I am getting the data but it does not return any thing to controller.
My service. js file
app.factory('countryService', function ($http) {
return {
getCountries: function () {
$http.get('http://abc/countries')
.success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
}
};
});
and here is my controller
$scope.countries = function () {
$scope.countries_data = countryService.getCountries();
console.log($scope.countries_data);
};
What is my mistake ?
You might need to do some structural changes like following
app.factory('countryService', function ($http) {
return {
getCountries: function () {
return $http.get('http://abc/countries'); //just return promise
}
};
});
Let service return the promise, Do other proceedings inside the controller,Define success callback and faiure callback for the same
$scope.countries = function () {
$scope.countries_data = countryService.getCountries().then(success, failure); // callbaks
};
function success(response){
console.log(response); // logs the results
}
function failure(response){
console.log(response); // logs the errors if any
}
Hope this will help
In your service:
app.factory('countryService', function ($http) {
return {
getCountries: function () {
return $http.get('http://abc/countries') // add return this service
.success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
}
};
});
In controller:
$scope.countries = function () {
countryService.getCountries().then(function(res){
$scope.countries_data = res;
console.log($scope.countries_data);
});
};

Angular pass parameters and receive json

I am using this service to get json data. How can I pass two parameters as well. With the json I need to populate a drop down.
myApp.service('allCurrentSettingsService', ['$http', '$q', function ($http, $q) {
var allSettings = null;
this.getList = function () {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings', { companyName: compName, customerName: custName })
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
}]);
And here I am calling the service:
myApp.controller('myController', ['$scope', 'getDocTypesService',
function ($scope, getDocTypesService) {
$scope.getDocTypes = '';
getDocTypesService.getList(compName, custName).then(function (value ) {
$scope.getDocTypes = value
});
}
]);
You missed the function parameters. Please add the same in function definition.
this.getList = function (compName, custName) {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings', { companyName: compName, customerName: custName })
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
You can call the $http.post() in other ways also:
var data = {param:'val1',.....}
$http({
url: "time.php",
method: "POST",
params: data
})

Console error, not sure way

I am getting this error.. not sure what's the problem..
TypeError: StatisticsService.getStatisticsFromServer is not a function
i cant seem to see the problem, not sure what i'm doing wrong
this is the controller
app.controller('StatisticsCtrl',
['$scope',
'$auth',
'StatisticsService',
function ($scope, $auth, StatisticsService) {
var token = $auth.getToken();
console.log('StatisticsCtrl INIT');
function run() {
var data = {
token: token,
timestamp_from: moment(new Date()).unix()-30 * 24 * 3600,
timestamp_till: moment(new Date()).unix(),
order: 'duration_minutes',
limit: 20
};
//
StatisticsService.getStatisticsFromServer(data).then(function (response) {
console.log('syncStatistics', (response));
$scope.statistics = response;
// $scope.statistics = StatisticsService.buildStatsUsers(response.data); // jason comes from here
}, function (error) {
console.error(error);
});
}
run();
}]);
this is the server
app.service('StatisticsService',
['apiClient', '$q', '$rootScope', '$timeout',
function (apiClient, $q, $rootScope, $timeout) {
var self = this;
self.getUserProfiles = function (stats) {
var emails = [];
for (var i = 0; i < stats.length; i++) {
emails.push(stats[i].email);
}
console.log(emails);
var data2 = {
token: data.token,
profile_emails: emails
};
apiClient.getUserProfiles(data2).then(function (response2) {
console.log('getUserProfiles', (response2));
if (response2.data.length === 0 || response2.result !== "success") {
// TODO: show error
deferred.reject(response2);
}
var stats2= response2.data;
deferred.resolve(stats);//3
}
);
self.getStatisticsFromServer = function (data) {
var deferred = $q.defer(); //1
apiClient.getStatsTopMeeters(data)
.then(function (response) { //2
console.log('externalApiConnect', response);
if (response.data.length === 0 || response.result !== "success") {
// TODO: show error
deferred.reject(response);
}
var stats = response.data;
stats = self.getUserProfiles(stats);
deferred.resolve(stats);//3
}
, function (error) {
deferred.reject(error);
console.error(error);
});
return deferred.promise; //4
};
};
}]);
You're defining self.getStatisticsFromServer inside the function self.getUserProfiles. So, the function indeed doesn't exist in the service until you call getUserProfiles() at least once. And it's replaced at each invocation. I doubt that's what you want.

Update in service not reflecting in controller. AngularJS

I've ProductService and ProductsController. ProductService have ProductService.Products = []; variable which contains all the Products information.
I access this Products-information in ProductsController and stores in variable named $scope.Products = [];.
Problem is some other service also using "ProductService", and updating "Products Info", using "UpdateInfo" function exposed in ProductService. Now these changes are not getting reflected in ProductsController variable $scope.Products = [];.
This is my code.
sampleApp.factory('ProductService', ['$http', '$q', function ($http, $q){
var req = {
method: 'POST',
url: 'ProductData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
var ProductService = {};
ProductService.Products = [];
return {
GetProducts: function () {
var defer = $q.defer();
$http(req).then(function(response) {
ProductService.Products = response.data;
defer.resolve(ProductService.Products);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
},
UpdateInfo: function (ProductID, VariantID) {
for (i in ProductService.Products) {
if (ProductService.Products[i].ProductID == ProductID) {
for (j in ProductService.Products[i].Variants) {
if (ProductService.Products[i].Variants[j].VariantID == VariantID) {
ProductService.Products[i].Variants[j].InCart = 1; /* Updating Info Here, But its not reflecting */
break;
}
}
break;
}
}
}
};
}]);
sampleApp.controller('ProductsController', function ($scope, $routeParams, ProductService, ShoppingCartService) {
$scope.Products = [];
$scope.GetProducts = function() {
ProductService.GetProducts().then
(
function(response) {
$scope.Products = response;
},
function(error) {
alert ('error worng');
}
);
};
$scope.GetProducts();
});
Can some one help me how to solve this issue?
You can create a $watch on ProductService.Products in your controller. When the value changes, you can update $scope.Products with the new value.
$scope.$watch('ProductService.Products', function() {
$scope.Products = ProductService.Products;
});
Try assigning ProductsService.Products to $scope.products.
$scope.GetProducts = function() {
ProductService.GetProducts().then
(
function(response) {
$scope.Products = ProductService.Products;
},
function(error) {
alert ('error worng');
}
);
};

Resources