Angular app http call custom service failing - javascript

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 !

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

AngularJS w/ Flask backend, representing the data passed from backend

I am working on an Single page app using angular with a python / flask back-end that links to mongodb.
The issue that I am having is that, once the data is passed from the back-end using a $http get request from angular as an object which I cannot seem to get to display in the front-end. I am able to display it in the console but I am puzzled as to why it will not display in the front end.
When I use a declared array of JSON objects in the factory the information passes through fine but, when using the data taken from the back-end it does not display.
I am also able to curl request the data required.
Thank you in advance for any help :)
.controller('topicCtrl', function(posts, $scope){
"use strict";
var p = this;
p.posts = posts.getPosts();
})
.factory('posts', function(data){
"use strict";
var posts={};
posts.item = data.response;
/*
- Add post function below -
post title & body to be entered
by the user.
The posts here will need to be passed down to a lower
layer, with aim of sending JSON Object w/ post request to
api.
*/
posts.getPosts = function(){
posts.item = data.getData();
};
posts.addPost = function(title, body){
data.postData(posts.item.push({title: title, body: body}));
};
return posts;
});
.factory('data', function($http, $log){
"use strict";
var data = {};
/*data.item = [{id: 1, title:"An Intro to A!", body:"Hello there AAA! :) "},
{id: 2, title:"An Intro to B!", body:"Hello there BBB! :)"},
{id: 3, title:"An Intro to C!", body:"Hello there! ccc:)"}
];*/
data.getData = function(){
var i = 0;
$http({
method: 'GET',
url: '/h',
type: 'application/json'
}).then(function success(response){
$log.info("1 get", response);
data = response.data;
$log.info(data.response);
}, function error(response){
$log.info(" damn"+response);
});
};
data.postData = function(data){
$http({
method: 'POST',
url: '/h'
}).then(function sucess(response){
$log.info(" hello from post"+response);
data.item = JSON.stringify(data.item);
}, function error(response){
$log.info(" damn from post "+response);
});
};
return data;
});
<div class="card card-block">
<l class="list" ng-repeat="post in list.posts">
</br>
<h4 class="card-title">{{post.title}}</h4>
<p class="card-text">{{post.body}}</p>
<!--- the functionality of the below will be added towards end, time permitting-->
Like
Comment
</br
</l>
</div>
</div>
some additional info that might be helpful:
image of the console
I've made some changes to the code below. Some variation of this will work.
.controller('topicCtrl', function(posts, $scope){
$scope.posts = [];
$scope.getPosts = function() {
posts.getPosts().then(function(response){
//success
console.log("Success Get");
console.log(response);
$scope.posts = response;
}, function(error){
//error
console.log("error");
});
};
})
.factory('posts', function(data){
"use strict";
var posts={};
posts.getPosts = function(){
return data.getData();
};
return posts;
});
.factory('data', function($http, $log){
"use strict";
var data = {};
data.getData = function(){
$http({
method: 'GET',
url: 'http://127.0.0.1:5000/h',
type: 'application/json'
});
};
return data;
});
for anyone who may need it in the future! :)
I added a for loop that iterates over the response data and stores each element into an array then returned the array.
data.getData = function(){
var i;
var myObj = [];
$http({
method: 'GET',
url: '/h'
}).then(function success(response){
$log.info(" hello the get", response.data);
for (i = 0; i < response.data.length; i++){
myObj[i] = (response.data[i]);
}
if(response.data.length === 0){
$log.info("empty set");
}else{
//data.item = response.data;
$log.info("SUCCESS!!" + myObj);
}
}, function error(response){
$log.info(" damn"+response);
});
return myObj;
};
.factory('posts', function(data, $log){
"use strict";
var posts={};
posts.item = data.getData();
posts.addPost = function(title, body){
data.postData(posts.item.push({title: title, body: body}));
};
$log.info("in the posts" + posts.item);
return posts;
});
.controller('topicCtrl', function(posts){
"use strict";
var p = this;
p.posts = posts.item;
})

how to use query with parameters in angularJS?

I need to use a query method in Angular JS service connecting to a restful web service with the url /users/userId/sensors/. The restful web service works fine when I enter the url in the browser but when I want to get the result in Angular service when calling the find method I get nothing.
controller.js:
appControllers.controller('sensorController',
function ($scope, Scopes, SensorService) {
var userId = Scopes.get('id');
$scope.sensors = [];
$scope.sensors = function () {
SensorService.find(userId, function (data) {
$scope.sensors = data;
});
};
});
service.js:
appServices.factory('SensorService', function ($resource) {
var url = '/iots-web/rest/users/:userId/sensors/:path';
return $resource(url, {path: '#path', userId: '#userId'}, {
query: {method: 'GET',isArray: true},
find: {method: 'GET', params: {userId: '#userId'}, isArray: true},
create: {method: 'POST'},
update: {method: 'PUT', params: {id: '#id'}},
delete: {method: 'DELETE', params: {id: '#id'}}
});
});
Scopes is another service I use to share the usrId between controllers and it works fine so there is no problem with getting the userId.
Correct way to pass userId into resource call would be:
SensorService.find({userId: userId}, function(data) {
$scope.sensors = data;
});
Also to avoid confusion, it's better to rename sensors function to something else:
$scope.sensors = [];
$scope.getSensors = function() {
SensorService.find({userId: userId}, function(data) {
$scope.sensors = data;
});
};
the problem looks as you are trying to access a javascript variable in an anonymous function
$scope.sensors = function () {
SensorService.find(userId, function (data) {
$scope.sensors = data;
});
userId does not exist in this anonymous function.
$scope.sensors = [];
$scope.sensors = function () {
SensorService.find(userId, function (data) {
$scope.sensors = data;
});
};
This seems suspicious to me. You first assign an empty Array to $scope.sensors, then override this value with a function, and then override it again with data, when it arrives.
Try fixing this first and then check if your problem still persists.

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

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

Angular factory ajax call on every route change

I have a factory where I have a function getExpenseList which does an ajax call which queries the expense table and gives me the result.
Now I have two routes, 1 which is listing of expenses which is pushing the expense through the above function and the second route is an add. When I do a route change and come back to the listing page, the ajax call is made again. Ideally I should be able to store the expense object on the first ajax call and then reference the same object till someone is manually refreshing the browser.
please help me on this. Here is my factory code. Ideally I would like to refer to this.expenses if the data is present.
admin.factory('expenseFact', ['$http', function($http) {
var expense = {};
this.expenses = "";
expense.getExpenseList = function() {
this.expenses = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
});
return this.expenses;
};
return expense;
}]);
And here is my controller code
admin.controller('expenseLandCtrl', function ($scope,$rootScope,expenseFact) {
$scope.pageTitle = $rootScope.pageTitle;
expenseFact.getExpenseList().then(function (data) {
$scope.expenses = data.data;
});
});
admin.controller('expenseAddCtrl', function ($scope,$rootScope,expenseFact) {
$scope.pageTitle = $rootScope.pageTitle;
});
your factory will be like this
admin.factory('expenseFact', ['$http', function($http) {
return {
getExpenseList: function() {
var expense = {};
this.expenses = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
});
return this.expenses;
}
}
}]);
and you can call it from controller same way and it wont call it automatically.
btw i recommend use of promises.
below is same code with use of promise
admin.factory('expenseFact', ['$http', '$q'. function($http, $q) {
return {
getExpenseList: function(){
var deferred = $q.defer();
$http({method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).
then(function(response) {
deferred.resolve(response.data);
}, function(response) {
deferred.reject(response.status)
});
return deferred.promise;
}
}
}]);
You need to get the expenses once when the factory is loaded for the first time;
admin.factory('expenseFact', ['$http', function($http) {
var expenses = null;
$http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
}).success(function (exp) {
expenses = exp;
}); // get the expenses when the factory is loaded
return {expenses: expenses};
}]);
What this does is that it makes the expenses return from the factory refer to the one-time ajax call to get the expenses.

Categories