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;
})
Related
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;
})
i'm developing an Ionic app and i must pass data from backend (php file on a server) to ionic app and from ionic app to backend.
I tried this:
.controller('AppCtrl',function($scope,$ionicPlatform,$location,$http,$ionicHisto
ry, $ionicModal, $timeout,$cordovaSQLite) {
$ionicPlatform.ready(function(){
$http.get('http://http://localhost/ShuttleFIX/json.php')
.success(function(data,status,headers,config){
var user = data;
for(i = 0; i<user.length; i++){
var cell = user[i].cell;
var nome = user[i].nome;
var cognome = user[i].cognome;
var mail = user[i].mail;
var codF = user[i].codF;
var pwd = user[i].pwd;
}
}
});
I know i must use http request but i don't know how, can someone help me?
Thank's
The first thing to determine is how you return and receive data from your server php. Define the method GET or POST, if GET you must assemble the URL with the parameters you want to send. If Post, they are usually shipped with JSON format and pass in the parameter data
It seems not beam tried a lot but is more or less like this:
GET :
.controller('AppCtrl', function($scope, $http){
var url = "http://myhost/name="+$scope.name;
$http({ method: 'GET', url: url, dataType: "json", contentType: "application/x-www-form-urlencoded" })
.success(function(data) {
console.log(data);
})
.error(function(response) {
console.log("error");
})
.finally(function() {
});
})
POST:
var data = {
name : $scope.name
}
$http({ method: 'POST', url: url, dataType: "json", data: data})
.success(function(data) {
})
.error(function(response) {
console.log("error");
})
.finally(function() {
});
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 !
I'm trying to call another function within my factory but i get this error. i did what others said in this link. i could not find the problem. where did i go wrong? Thanks!
.factory('UserPreferences',function(Http,ngDialog,Notification){
var settings = {}
return {
authenticated: false,
settings:{},
saveSettings: function(data){
var data = {
url: '/pointofsale/userpreferences/save',
data: data
}
Http.Post(data)
.success(function(data){
statusMessage = data
ngDialog.closeAll(0)
})
},
authenticate_change_settings: function(user,settings){
this.settings = settings
var data = {
url: '/pointofsale/authenticate_change_settings',
data: user
}
Http.Post(data)
.success(function(data){
if(data){
this.authenticated = true;
this.saveSettings(this.settings);
}
}).error(function(data){
Notification.error(data)
})
}
}
Update: so i found the problem, i can't call the function within the
$http post call success function. why is this happening?
So, i tried doing this. and it works, it called the function. not sure if this is proper.
authenticate_change_settings: function(user){
var $this = this;
var data = {
url: '/pointofsale/authenticate_change_settings',
data: user
}
Http.Post(data)
.success(function(data){
if(data){
$this.authenticated = true;
$this.saveSettings(this.settings);
}
}).error(function(data){
Notification.error(data)
})
}
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()