Access database from angular component with service - javascript

I am trying to populate my combo box from the database on page load. When I debug it, debug point don't hit at adminsService.test(result) at all. Why is that? I am trying to get the data without any conditions.
angular.module('adminService', []).factory('adminService', function ($rootScope, $http) {
var modelService = function () {
}
modelService.prototype.test = function (test) {
var promise = $http(
{
method: 'POST',
url: '/Model/getTopics',
contentType: 'application/json',
data: {
test: test
}
});
return promise;
}
viewRoleModule.controller('viewRoleController', function ($scope, $routeParams, adminService) {
var self = this;
self.$onInit = function () {
self.topicRoleItems = function ()
{
adminService.test(result);
};
}
});
<div ng-repeat="item in $ctrl.topicRoleItems">
{{item.TopicName}}
</div>

Try
self.topicRoleItems = adminService.test().then(function(result){
self.topicRoleItems = result;
});
UPDATE
.factory('adminService', function ($rootScope, $http,$q) {
var modelService = [];
modelService.test = function (test) {
var deferred = $q.defer();
$http({
method: 'POST',
url: '/Model/getTopics',
contentType: 'application/json',
data: {
test: test
}
}).success(function(resp){
deferred.resolve(resp);
}).error(function(resp){
deferred.reject();
});
return deferred.promise;
}
return modelService;
})

Related

How to get promise result using AngularJS

The following is the controller used to retrieve information from sharepoint. I can see debugging that the entry data.d.UserProfileProperties.results[115].Value has a property value that I need to render in view. How can I get that value from the result promise?
(function() {
'use strict'
var createPurchasingCardController = function($scope, $rootScope, $filter, $window, $location, $timeout, requestService) {
$scope.actionTitle = "";
$scope.counter = [];
var getCurrentUserData = function () {
var dfd = new $.Deferred();
var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
$.ajax({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: onSuccess,
error: onError,
cache: false
});
function onSuccess(data) {
dfd.resolve(data);
}
function onError(data, errorCode, errorMessage) {
dfd.reject(errorMessage);
}
return dfd.promise();
}
var _init = function () {
$scope.counter = getCurrentUserData();
console.log($scope.counter);
}
_init();
}
angular.module('myApp').controller('createPurchasingCardController', ['$scope', '$rootScope', '$filter', '$window', '$location', '$timeout', 'requestService', createPurchasingCardController]);
}());
I have tried to get it into the counter but it is not showing up. Any help would be appreciated.
Instead of using jQuery .ajax, use the $http service:
function getCurrentUserData() {
var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
var promise = $http({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
cache: false
}).then(function(response) {
return response.data;
}).catch(function(response) {
console.log("ERROR", response);
throw response;
});
return promise;
}
Then extract the data from the returned promise:
function _init() {
var promise = getCurrentUserData();
promise.then(function(data) {
$scope.counter = data;
console.log($scope.counter);
});
}
_init();
The promises returned by the $http service are integrated with the AngularJS framework. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.
For more information, see
AngularJS $http Service API Reference
assign your response object to $scope object
function onSuccess(data) {
$scope.promiseData = data
dfd.resolve(data);
}

Angular JS Service Creation Error

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
}
}

How to make View redirects in AngularJS without constant server requests

Everytime when I make View redirect (I use href to do so) I can see that AngularJS runs GetAjaxData1, GetAjaxData2.
In the other words: instead of the single initial request to the server, I do it everytime when I make View redirection. What is wrong?
Here is my AngularJS code:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
var factory = {};
data1 = [];
data2 = [];
factory.getAjaxData1 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data1 = result;
}
});
return data1;
};
factory.getAjaxData2 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data2 = result;
}
});
return data2;
}
};
var controllers = {};
controllers.uController = function ($scope, $location, uFactory) {
$scope.data1 = uFactory.getAjaxData1();
$scope.data2 = uFactory.getAjaxData2();
};
You definitely have to read about $http and ng-resource library and
try more angular way in your application and you also should
understand that ajax request is always asynchronous, and try to
understand promise pattern.
Technically - what you need is a caching - no matter how you are going to implement this - you need to make a single call to the API and the to cache variable.
I don't like idea of usage $.ajax, but it can look like this:
angular.module('myApp').config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
return {
getFirstPromise: function () {
if (!this.$$firstPromise) {
this.$$firstPromise = $.ajax({
url: url,
type: 'GET',
contentType: "application/json"
}).then(function (data) {
window.data1 = data;
});
}
return this.$$firstPromise;
}
... //some other code
}
});
var controllers = {
uController: function ($scope, $location, uFactory) {
uFactory.getFirstPromise().then(function (data) {
$scope.data1 = data;
});
// same for other data - and don't try to make ajax requests synhronous ;-)
}
};
Controllers are not singletons. So your "UController" is created everytime your view changes. I assume that the factory is used inside this controller. See: What is the lifecycle of an AngularJS Controller?

$http post via an angularjs service

I use the code below. The content of dataService is all the $http possible in my application. In the controller, I consume this function. The function call a Web Api service, this one is called and return the right response. In the function customerToggleSuccess the data is undefined. I don't understand why.
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
.then(customerToggleData)
.catch(customerToggleError)
}
function customerToggleData(response) {
return response.data;
}
function customerToggleError(response) {
}
}
}());
(function () {
angular.module('myApp')
.controller('customerController', ['$scope', 'dataService', '$http', '$log', CustomerController]);
function CustomerController($scope, dataService, $http, , $log) {
var vm = this;
vm.activeToggle = function (customerId, index) {
dataService.customerToggleActive(customerId, index)
.then(customerToggleSuccess)
.catch(customerToggleCatch)
.finally(customerToggleComplete);
function customerToggleSuccess(data) {
$log.info(data);
}
function customerToggleCatch(errorMsg) {
}
function customerToggleComplete() {
}
}
}
}());
Like this ,
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
}
}
}());
Simply return the $http promise,
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
you can access it by,
dataService.customerToggleActive(customerId, index)
.then(function (response) {
// do your stuff
})
or, you can do,
function dataService($q, $http,) {
var defer = $q.defer();
....
....
$http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
function customerToggleData(response) {
defer.resolve (response.data);
}
function customerToggleError(response) {
defer.reject(response);
}
return defer.promise;
}

Use parameters in angular factory for custom header

I'm trying to find a way to pass a parameter so I can use it in my 'endpoint' variable, as you can see in my code I have the url and in the end of it I have "/clientes", but, in my API I also have "products" and "travels", so I'm looking for a solution to use a variable so I can change the end of the url, otherwise I'll have to create another factories just to get my "products" and my "travels".
angular.module('starter.services', [])
.factory('ServiceClientes', ['$http', function ($http) {
var endpoint = 'http://api.rep.com/api/clientes';
var token = '99KI9Gj68CgCf70deM22Ka64chef2J2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8';
var credencial = 'rm#w.com:cd8cdx5ef753a06ee79fc75dc7cfe66c';
var origem = 'mobile';
var config = {
url: endpoint,
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function () {
return $http(config);
}
};
}]);
controller:
.controller('PlaylistsCtrl', function ($scope, ServiceClientes) {
ServiceClientes.getAll().success(function (data) {
$scope.playlists = data.dados;
}).error(function (error) {
console.log(error);
});
})
Then make your function injectable with a parameter:
var endpoint = 'http://api.rep.com/api/';
var config = {
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function (url) {
config.url = endpoint + url;
return $http(config);
}
};
controller:
ServiceClientes.getAll("clientes").success(function (data) {

Categories