Can I pass values from $http.get to another functions in AngularJS - javascript

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()

Related

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

Angular app http call custom service failing

I'm making a little angular app to show info about the english premier league. I want to make a service to deal with making http calls cos I do it a few times on the page and I don't want to repeat everything. Here is my table.js TableController, which is used for building a league table/
(function(){
angular
.module("eplApp")
.controller("tableCtrl", TableController);
TableController.inject = ['httpService'];
function TableController(service){
var apiUrl = "http://api.football-data.org/v1/soccerseasons/426/leagueTable";
service.getListFromUrl(apiUrl).then(function(data){
var vm.this;
vm.data = response.data;
});
}
})();
And here is the service I've made to run the http requests, service.js:
(function(){
angular
.module("eplApp")
.factory("httpService", httpService);
httpService.inject = ['$http'];
function httpService($http){
var apiKey = '971acba677654cdb919a7ccebd5621e2';
var vm = this;
vm.data = [];
$http({
headers: { 'X-Auth-Token': apiKey },
method: "GET",
url: apiUrl
}).then(function(response) {
vm.data = response.data;
return vm.data;
});
}
})();
When I run it I get the following error:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=serviceProvider%20%3C-%20service%20%3C-%20tableCtrl
Where am I going wrong here?
Check the controller you used, the controller function paramater is httpService, and you used inside is HttpService. Please chaeck that, Its case sensitive.
Try with change your service like that:
(function(){
angular
.module("eplApp")
.factory("httpService", httpService);
httpService.$inject = ['$http'];
function httpService($http){
return {
getListFromURL : getListFromURL
}
function getListFromURL(apiUrl){
var apiKey = '971acba677654cdb919a7ccebd5621e2';
var vm = this;
vm.data = [];
return $http({
headers: { 'X-Auth-Token': apiKey },
method: "GET",
url: apiUrl
}).then(function(response) {
vm.data = response.data;
return vm.data;
});
}
})();
And call the function in controller like this:
TableController.$inject = ['httpService'];
function TableController(service){
var apiUrl = "http://api.footballdata.org/v1/soccerseasons/426/leagueTable";
service.getListFromURL(apiUrl).then(function(data){
//data here is vm.data
});
}
Hope this help !

service does not return data to controller in angular

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;
}
}]);

How to test an http request in my case?

I have a service like this.
It is simply just make a http get request.
angular.module('myApp').service('TESTService', ['$http',
function($http) {
var request = function(url) {
return $http({
method: 'GET',
url: url
});
};
return {
get: function(url) {
return request(url);
}
};
}
]);
Within my controller, I have called the service
TESTService.get('/api/product' + id).success(
function(result) {
console.log(result)
}
);
I need to write the unit test for it
describe('test here', function () {
var testCtrl, scope, httpBackend, testService;
// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _TESTService_) {
scope = _$rootScope_.$new();
httpBackend = _$httpBackend_;
testService = _TESTService_;
testCtrl = _$controller_('testCtrl', {
$scope: scope
});
it('should return http data', function() {
var productData = {
data: [
{
obj: {
id:'123'
}
}
]
}
httpBackend.expectGET('/api/product/' + id).respond(productData);
TESTService.get('/api/product/' + id).
then(function(data) {
var result = data;
})
httpBackend.flush();
expect(result).toEqual(productData)
});
}));
After running the test, I got
Error: Unexpected request: GET /api/product/undefined
How do I write the test to make sure it passes? Any ideas? Thanks a lot!
Your variable "id" seems to be undefined. If you throw in
var id = 123;
before this line:
httpBackend.expectGET('/api/product/' + id).respond(productData);
It would call /api/product/123 instead.
So maybe you were looking for this in the first place:
httpBackend.expectGET('/api/product/' + productData.data[0].obj.id).respond(productData);
TESTService.get('/api/product/' + productData.data[0].obj.id).
And so on... Hope it helps!
Try putting single quotes around the object that's passed into $http, i.e. $http({method: 'GET', 'url', url});
angular.module('myApp').service('TESTService', ['$http',
function($http) {
var request = function(url) {
return $http({
method: 'GET',
'url': url
});
};
return {
get: function(url) {
return request(url);
}
};
}
]);

sharing $scope between 2 function within one controller

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);
});
});
}
}
}]);

Categories