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);
}
Related
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
}
}
Here is my service:
app.service('trackService', ['$http', function($http) {
var data;
this.topTracks = function(limit) {
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks; console.log(this.data); return this.data;
});
}
}]);
and controller -
app.controller('artistSongsCtrl', ['$scope', 'trackService', function($scope, trackService) {
$scope.data = trackService.topTracks(10);
//console.log($scope.data);
}]);
how to send data to the controlller using a $http service inside a custom service?
Several problems are $http is asynchronous and your service method topTracks() doesn't return anything. Also you can't return inside success, there is nowhere to return to ... use then() instead
You need to return the promise from service and set the scope in a promise callback in controller
app.service('trackService', ['$http',
function($http) {
var data;
var self = this;
this.topTracks = function(limit) {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {
api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf',
format: 'json',
limit: limit
}
}).then(function(result) {
self.data = result.data.tracks;
console.log(self.data);
return self.data;
});
}
}
]);
app.controller('artistSongsCtrl', ['$scope', 'trackService',
function($scope, trackService) {
trackService.topTracks(10).then(function(data) {
$scope.data = data;
//console.log($scope.data);
});
}
]);
Inside your service you are making an asynchronous GET request. In order to let the controller catch that response, you need to return a promise. Here's an example using $q:
app.service('trackService', ['$http', '$q', function($http, $q) {
var data;
this.topTracks = function(limit) {
var d = $q.defer();
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks;
console.log(this.data);
d.resolve(this.data);
});
return d.promise;
}
}]);
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?
For a functionality that I need, I found a really nice AJAX example. Basically it calls the Yahoo API. But I'm working with Angular.JS. So I have no clue how to convert that. Any help?
That's the AJAX function (details see this posting and this JsFiddle):
$.ajax({
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
data:{
query: request.term
},
url: 'http://autoc.finance.yahoo.com/autoc',
success: function (data) {
alert("yes");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
So what I'm looking for, is how to convert the code above into somewhat like this. The sample should just print the return value. See this JsFiddle. Especially, I have not idea what to do with the jsonpCallback parameter. That's what I could not find in any other example.
<div ng-app='MyModule' ng-controller='DefaultCtrl'>
{{ test() }}
</div>
JavaScript
function DefaultCtrl($scope, myService) {
$scope.test = myService.test;
}
angular.module('MyModule', [])
.factory('myService', function () {
return {
test: function () {
$http.get("?????")
.success(function(data, status, headers, config) {
return data;
})
.error(function(data, status, headers, config) {
return "there was an error";
})
}
}
});
The intermediate solution - after all your help - looks like this. Thanks. I had to install a Chrome extension which allows cross-domain calls as long as you use the updated JsFiddle. I changed the way I'm passing the parameters to the http-get call and I also included the $q (promise) handling. The result contains a valid list from Yahoo YQL API. Just need to handle that array then.
function DefaultCtrl($log, $scope, $http, myService) {
var promise = myService.getSuggestions('yahoo');
promise.then(
function(payload) {
$scope.test = payload;
$log.info('received data', payload);
},
function(errorPayload) {
$log.error('failure loading suggestions', errorPayload);
});
}
angular.module('MyModule', [])
.factory('myService', function ($http, $log, $q) {
return {
getSuggestions: function (symbol) {
var deferred = $q.defer();
$http.get('http://d.yimg.com/autoc.finance.yahoo.com/autoc', {
cache: true,
params: {
query: symbol,
callback: 'YAHOO.Finance.SymbolSuggest.ssCallback'
}
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(msg, code) {
deferred.reject(msg);
$log.error(msg, code);
});
return deferred.promise;
}
}
});
just have a look at the docs
https://docs.angularjs.org/api/ng/service/$http
$http.get('http://autoc.finance.yahoo.com/autoc',
{dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback'}).success(function(data){ alert("yes"); });
Use Ajax call and you have to use promise
And use only test not {{test()}}
Because in your controller when you call your factory ajax function then in controller you get undefined response.
So use promise.
Service:
var demoService = angular.module('demoService', [])
.service('myService',['$http', function($http) {
this.getdata = function(entity){
var promise = $http({
method : 'GET',
url : 'services/entity/add',
data : entity,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
headers : {
'Content-Type' : 'application/json'
},
cache : false
}).then(function (response) {
return response;
});
return promise;
};
}]);
Controller :
var demoService = angular.module('demoService', [])
.controller('myctr',['$scope','myService',function($scope,myService){
myService.getdata().then(function(response){
//Success
},function(response){
//Error
});
}]);
now you can see your json in controller success
I'm trying to use angular promise using $q that is wrapped in 'service' and call it from my controller.
Here is the code:
var myController = function ($scope, myService) {
$scope.doSomething = function (c, $event) {
$event.preventDefault();
myService.method1(c).then(function (rslt) {
alert(rslt);
}, function (err) {
alert(err);
}).then(function () {
//clean up
});
};
};
var myApp = angular.module('myApp', [])
.factory('myService', function($q) {
function _method1(c) {
var dfr = $q.defer();
var dt = { sc: c };
$.ajax({
type: "POST",
url: "mypage.aspx/mymethod",
data: JSON.stringify(dt),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
dfr.resolve('actions sucess');
},
error: function (msg) {
dfr.reject(msg);
}
});
return dfr.promise;
}
return { method1: _method1 };
}).controller('myController', myController);
The problem is that ' alert(rslt);' piece of code is never executed.
Service is called and data is updated but first 'then' function is not reached on first click.
What am I doing wrong?
Any help appreciated.
I would recoomend you to use $http and $resource instead of $.ajax
Heres an example of $http
myApp.factory('MyService',
[
'$http',
'$q',
'$resource',
function (
$http,
$q,
$resource
) {
return {
doSomething : function (somedata) {
var deferred = $q.defer();
$http({ method: 'POST', url: '"mypage.aspx/mymethod"', data: somedata }).
success(function (data, status, headers, config) {
deferred.resolve(true);
}).
error(function (data, status, headers, config) {
deferred.resolve(false);
});
return deferred.promise;
}
};
}]);
Just add the dependency to $rootScope and call $rootScope.$apply() in both callbacks from $.ajax():
success: function () {
dfr.resolve('actions sucess');
$rootScope.$apply();
}, ...
But better yet, use Angular's $http service.