app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){
$scope.ionLoader = true;
getTopicContent.request($stateParams.topicId).then(function(response){
$scope.threadContent = response.data;
}).finally(function(){
$scope.ionLoader = false;
});
$scope.loadPages = function ($scope) {
if(totalPages > 1){
$http({
url: "http://someurl.php",
method: "GET",
params: {topicId: $stateParams.topicId,page : 2}
}).success(function(data){
$scope.threadContent.push(data);
});
}
}
}]);
I got an error saying push of undefined. loadPages only fire when the user scrolled to the bottom of the page so I don't think it's an async issue, probably $scope problem? getTopicContent is my service.
You can use promise for async working and remove parameter $scope in loadPages like that:
app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){
$scope.ionLoader = true;
var promise = getTopicContent.request($stateParams.topicId).then(function(response){
$scope.threadContent = response.data;
}).finally(function(){
$scope.ionLoader = false;
});
$scope.loadPages = function() {
if(totalPages > 1){
$http({
url: "http://someurl.php",
method: "GET",
params: {topicId: $stateParams.topicId,page : 2}
}).success(function(data){
promise.then(function(none) {
$scope.threadContent.push(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;
}
}]);
I've set a factory with callback for success and error. However when I use it in the controller I need to alway define both success and error functions if I don't define a error callback function, it won't work.
Is there anyways that could make error callback optional when it needs to be use.
Controller
$scope.saveUsername = function(){
atFactory.saveUsername($scope, function(){
// this is success
}, function(){
// this is error
});
}
Factory
at.factory('atFactory', ['$http' , function ( $http ){
var factory = {};
factory.saveUsername = function($scope,callback){
$scope.url = '/member/username';
$scope.post_data = {
username : $scope.username
};
factory.doPostHttpRequest($scope).success(callback).error(callback);
}
factory.doPostHttpRequest = function($scope){
return $http({
url : $scope.url,
method: 'POST',
data: $scope.post_data
})
}
return factory;
}]);
My suggestion to you is to return the $http promise back to the controller, then you can call the success() in your controller (and optionally error()).
So in your factory:
factory.saveUsername = function($scope){
$scope.url = '/member/username';
$scope.post_data = {
username : $scope.username
};
return factory.doPostHttpRequest($scope);
}
factory.doPostHttpRequest = function($scope){
return $http({
url : $scope.url,
method: 'POST',
data: $scope.post_data
})
}
Then in your controller, you can do:
atFactory.saveUsername($scope)
.success(function(response) {
// success callback (optional)
})
.error(function(error) {
// error callback (optional)
});
you can use :
at.factory('atFactory', ['$http' , function ( $http ){
var factory = {};
factory.saveUsername = function($scope,successCallBack, errorCallBack){
$scope.url = '/member/username';
$scope.post_data = {
username : $scope.username
};
return factory.doPostHttpRequest($scope).success(function(){
if(successCallBack){
successCallBack();
}
}).error(function(){
if(errorCallBack){
errorCallBack();
}
});
}
factory.doPostHttpRequest = function($scope){
return $http({
url : $scope.url,
method: 'POST',
data: $scope.post_data
})
}
return factory;
}]);
I'm trying to learn AngularJS, and I'm wondering if I can do this or not?:
Here is my code:
(function() {
function InfoController($scope,$element){
$scope.items = data['data']; //data in Option controller
}
function OptionController($scope,$element,$http){
$element.find(".list-group-item").click(function() {
var a = $(this).text();
$http({
url: 'hand',
method: "GET",
params: {a: a},
}).success(function(data){
console.log(data['data'][0]);
});
});
}
angular.module('testModule', [])
.controller('InfoController', InfoController)
.controller('OptionController', OptionController);
})();
I'm new in AngularJS and I don't know how to pass values data['data'] from $http.get in OptionController to InfoController, so please tell me how can I do that :)
Yes, you would do so with a service docs
app.service('dataService', function(http) {
this.data;
var self = this;
this.getData = function() {
return $http.get('/data').then(function(resp) {
self.data = resp.data;
return self.data
})
}
you would then pass in dataService to both controllers
$scope.data = dataService.getData()
I am new angularJS.
I have make call more then 10 $http request using services in my project.
One service code is given below.
loginApp.factory('serviceAuth', function($http) {
return {
fnLoginAuth : function(aut,resp){
return $http({
method: 'GET',
url: 'http://localhost:8080/myProjectname/serviceName',
}).success(function(result) {
return result;
});
}
}
});
I want http://localhost:8080/myProjectname/ this part of url is configurable or use a variable instead of this URL.
In my applications written in AngularJS, I just put the variable in the $rootScope.
app.run(['$rootScope',
function($rootScope) {
$rootScope.serverRoot = '/projectname/public';
}
]);
And append it to the services.
this.addTask = function(data) {
return $http.post($rootScope.serverRoot + '/task/create', data);
}
Why don't you add another service that returns the base URL?
app.factory('urlService', function() {
var url = "";
return {
setUrl : function(newUrl){
url = newUrl;
},
getUrl : function(){
return url;
}
}
});
and use it like this:
app.run(function(urlService) {
urlService.setUrl('http://localhost:8080/myProjectname/');
})
loginApp.factory('serviceAuth', function($http, urlService) {
return {
fnLoginAuth : function(aut,resp){
return $http({
method: 'GET',
url: urlService.getUrl() + 'serviceName',
}).success(function(result) {
return result;
});
}
}
});