Unable to retrieve data via AngularJS $http service factory - angularjs

I am new to AngularJS and Ionic. I have the following problem. I cannot pass the data from the factory service to the controller and scope.
May I know what is the problem?
service.js
angular.module("starter")
.factory("newsFeedService", function($http){
var feedService={};
feedService.retrieve = function() {
$http.get("https://jsonplaceholder.typicode.com/posts/")
.then(function(response) {
return response.data;
})
.catch(function(response) {
console.log("Error retrieving data.")
})
.finally(function(response) {
console.log("End of service.")
})
}
return feedService;
})
controller.js
angular.module("starter")
.controller("newsFeedController", function($scope, newsFeedService) {
$scope.newsFeeds = newsFeedService.retrieve(function(data));
console.log($scope.newsFeeds);
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link rel="manifest" href="manifest.json">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/service.js"></script>
<script src="js/controller.js"></script>
</head>
<body ng-app="starter" ng-controller="newsFeedController">
<ion-pane>
<ion-header-bar class="bar-positive">
<h1 class="title">SG News Feed </h1>
</ion-header-bar>
<ion-content>
<ul ng-repeat="newsFeed in newsFeeds">
<li>{{newsFeed.title}}</li>
</ul>
</ion-content>
</ion-pane>
</body>
</html>

Your function does not return the response of your http call but a promise.
Correct your controller as follow:
angular.module("starter")
.controller("newsFeedController", function($scope, newsFeedService) {
$scope.newsFeeds ={};
$scope.loadNews = function(){
newsFeedService.retrieve(function(data){
// the server returns the news: you can use them in your scope
$scope.newsFeeds = data;
});
}
$scope.loadNews();
})

// on service
feedService.retrieve = function(successCallback, failedCallback) {
$http.get("https://jsonplaceholder.typicode.com/posts/")
.then(successCallback, failedCallback);
}
// on controller
$scope.newsFeeds = null;
newsFeedService.retrieve(function(response){
$scope.newsFeeds = ......;
console.log($scope.newsFeeds);
},
function(response){
console.log("Oops! somethings went wrong!");
});
Try above code. Because $http.get is asynchronous, so I think all data handling should be done in callback function.
You can read more detail on AngularJS document: $http service document

Try following code.
angular.module("starter")
.factory("newsFeedService", function($http, $q) {
var retrieve = function() {
var deferred = $q.defer();
$http.get("https://jsonplaceholder.typicode.com/posts/")
.then(function(response) {
deferred.resolve(response);
})
.catch(function(response) {
console.log("Error retrieving data.")
deferred.reject(response);
})
.finally(function(response) {
console.log("End of service.")
})
return deferred.promise;
}
return {
retrieve: retrieve
};
})
/*Because $http.get return promise you can use following way as well without $q service*/
.factory("newsFeedService", function($http) {
var retrieve = function() {
return $http.get("https://jsonplaceholder.typicode.com/posts/");
}
return {
retrieve: retrieve
};
})
angular.module("starter")
.controller("newsFeedController", function($scope, newsFeedService) {
newsFeedService.retrieve().then(function(data) {
$scope.newsFeeds = data
}, function(data) {
console.log(data);
});
console.log($scope.newsFeeds);
})

You have to return promise from the retrieve function like so :
angular.module("starter")
.factory("newsFeedService", function($http){
var feedService={};
feedService.retrieve = function() {
return $http.get("https://jsonplaceholder.typicode.com/posts/") // "return" is the key here
.then(function(response) {
return response.data;
})
.catch(function(response) {
console.log("Error retrieving data.")
})
.finally(function(response) {
console.log("End of service.")
})
}
return feedService;
})
and then in controller :
angular.module("starter")
.controller("newsFeedController", function($scope, newsFeedService) {
newsFeedService.retrieve()
.then(function(data){
$scope.newsFeeds = data;
console.log($scope.newsFeeds);
})
.catch(function(){
})
})

Related

Angular injector error with Filestack

I am attempting to integrate Filestack into an existing app. I think I am having issues with how those modules are configured, but can't get the ordering correct. I receive this error:
angular.js:38Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.6/$injector/modulerr?p0=myApp&p1=TypeError%…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.6%2Fangular.min.js%3A20%3A156)
Here is the routing file:
(function () {
var app = angular.module('myApp', ['ngRoute', 'angular-filepicker']);
// ROUTING
app.config(['$routeProvider', function($routeProvider, filepickerProvider){
$routeProvider
.when('/home', {
templateUrl: "views/home.html",
controller: "HomeController"
})
.when('/shopping-list/:id', {
templateUrl: "views/shopping-list.html",
controller: 'ShoppingListController'
})
.when('/add-list', {
templateUrl: "views/add-list.html",
controller: 'AddListController'
})
.otherwise({
redirectTo: '/home'
});
filepickerProvider.setKey('XXXXXXX');
}]);
Here is the index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<!-- CDN SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/randomcolor/0.4.4/randomColor.min.js"></script>
<!-- Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Tara's Custom CSS -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!-- Imported Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
<title>Shopping List</title>
</head>
<body>
<div ng-include="'partials/header.html'"></div>
<main ng-view></main>
<!--ANGULAR SCRIPTS-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js"></script>
<script src="/bower_components/filepicker-js/filepicker.js"></script>
<script src="/bower_components/angular-filepicker/dist/angular_filepicker.js"></script>
<script type="text/javascript" src="//api.filestackapi.com/filestack.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/controllers/controller-header.js"></script>
<script type="text/javascript" src="js/controllers/controller-home.js"></script>
<script type="text/javascript" src="js/controllers/controller-add-list.js"></script>
<script type="text/javascript" src="js/controllers/controller-shopping-list.js"></script>
</body>
</html>
And the controller that is using Filestack:
(function () {
'use strict';
var app = angular.module('myApp');
app.controller('ShoppingListController', ['$scope', '$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, filepickerService, $routeParams, API_BASE, $location){
// GET SPECIFIC LIST
$scope.list = [];
var id = $routeParams.id;
$http({
method: 'GET',
url: API_BASE + 'shopping-lists/' + id
}).then(function successCallback(response) {
$scope.list = response.data[0];
}, function errorCallback(response) {
console.log('it did not work');
console.log(response.statusText);
});
// REMOVE LIST
$scope.removeList = function(){
var id = $scope.list.id;
console.log(id);
$http.delete(API_BASE + 'shopping-lists/' + id)
.success(function (data, status, headers, config) {
console.log('you deleted :' + $scope.list);
})
.error(function (data, status, header, config) {
});
$location.path('/home');
};
// RANDOM ID
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
text += Date.now();
return text;
}
// ADD ITEM
$scope.addItem = function(){
var created = new Date();
var newID = makeid();
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
name : $scope.newItem.name,
priority : $scope.newItem.priority,
note: $scope.newItem.note,
picture: $scope.newItem.picture,
isChecked: false,
listId: $scope.list.id,
created: created,
id: newID
});
// console.log($scope.list.items);
$http.put(API_BASE + 'shopping-lists/', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
// Reset input fields after submit
$scope.newItem = {
name: "",
priority: "",
note: ""
};
};
// ADD ITEM IMAGE
$scope.upload = function(){
filepickerService.pick(
{
mimetype: 'image/*',
language: 'en',
services: ['COMPUTER','DROPBOX','GOOGLE_DRIVE','IMAGE_SEARCH', 'FACEBOOK', 'INSTAGRAM'],
openTo: 'IMAGE_SEARCH'
},
function(Blob){
console.log(JSON.stringify(Blob));
$scope.newItem.picture = Blob;
$scope.$apply();
});
};
// REMOVE ITEM
$scope.removeItem = function(item){
var removedItem = $scope.list.items.indexOf(item);
$scope.list.items.splice(removedItem, 1);
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// CLEAR ITEMS
$scope.clearItems = function(){
$scope.list.items.length = 0;
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// CLEAR CHECKED ITEMS
$scope.clearCheckedItems = function(){
var length = $scope.list.items.length-1;
for (var i = length; i > -1; i--) {
if ($scope.list.items[i].isChecked === true) {
$scope.list.items.splice(i,1);
}
}
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
//Edit Items / Checked Items
$scope.editItem = function(){
$http.put(API_BASE + 'shopping-lists', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
};
// SORT ITEMS
$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
}]);
}());
Right now, I can't get the page to load at all. Something isn't being called properly, I just can't figure out how to get the page to load (getting the Filestack to function properly is secondary right now).
Any suggestions with the configuration?
You do not have to declare a module for your controller,
var app = angular.module('myApp');
Change like this also you are missing 'filepickerService' while inecting,
angular.module('myApp').controller('ShoppingListController', ['$scope', '$http','filepickerService', '$routeParams', 'API_BASE', '$location', function($scope, $http, filepickerService, $routeParams, API_BASE, $location){

My Angular JS code is not working

I wrote some Angular JS code by learning from a tutorial. But in that video tutorial, the code works properly, but my code is not working. My web page is showing a blank page.
The index.html:
<div body ng-app="angularTable">
<div class="all_cat_main" ng-controller="listdata">
<div class="all_cat" ng-repeat="state in statelist">
<h2>{{state.Satename}}</h2>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="~/Content/AppJS/AllSate.js"></script>
And the AllSate.js
var app = angular.module('angularTable', []);
app.controller('listdata', function ($scope, $http) {
$scope.statelist = [];
$.ajax({
url: "/JobWebApi/getDataForAngularGrid",
dataType: 'jsonp',
method: 'GET',
data: '',
})
.success(function (response) {
$scope.statelist = response;
})
.error(function (error) {
alert(error);
});
});
Please someone guide me why the code is not working ?
Please Remove injected $http from Controller and Firstly Load Jquery lib file.(http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js)
var app = angular.module('angularTable', []);
app.controller('listdata', function ($scope) {
$scope.statelist ="";
$.ajax({
url: "http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo",
dataType: 'jsonp',
method: 'GET',
data: '',
}).success(function (response) { debugger;
$scope.statelist = response.status;
$scope.$apply();
})
.error(function (error) {
alert(error);
});
});
<html ng-app="angularTable">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body ng-controller="listdata">
<div >
<div >
<h2>{{statelist.message}}</h2>
</div>
</div>
</body>
</html>

Can not sign in with google in angular

i am trying angular for the first time. i am trying to sign in with google account. But It is not working. When i load the page the button appears and then after loading it hides. and the code is not working to.
here is my app.html
<body >
<div ng-app="app" ng-controller="AppCtrl as app">
<button ng-click="update()">Post data</button>
</div>
<div ng-controller="SignCtrl">
<span id="signinButton" >
<span class="g-signin" ng-click="signIn()"></span>
</span>
<button onclick="SignedOut();">SignedOut</button>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script type="text/javascript" src="appMy1.js"></script>
<script type="text/javascript" src="GSignIn.js"> </script>
</body>
Here is my controller
var app = angular.module("app", []);
app.factory("GPlusAuthService", function ($q, $window) {
var signIn;
signIn = function () {
var defered = $q.defer();
$window.signinCallback = function (response) {
$window.signinCallback = undefined;
defered.resolve(response);
};
gapi.auth.signIn({
clientid: "389760997134-uredjv5rat0k3vsjaqlt7nn4pbgtqrat.apps.googleusercontent.com",
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schemas.google.com/AddActivity",
scope: "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read",
callback: "signinCallback"
})
return defered.promise;
};
return {
signIn: signIn
}
});
app.controller("AppCtrl", function($scope,$http) {
$scope.update=function(){
$http.post("/user/signup",{Name:'Mr.x',Email:'AX#gmail.com',Organisation:'Ruet',PlacesLived:'dhaka',Img_url:'xyz'})
.success(function(data, status, headers, config) {
console.log(headers);
})
.error(function(data, status, headers, config) {
//console.log(data);
console.log(headers);
});
}
}),
app.controller('SignCtrl', function ($scope, GPlusAuthService) {
$scope.signIn = function() {
GPlusAuthService.signIn().then(function(response) {
});
}
});
Any clue what i am doing wrong?
The error is "cookiepolicy is a required field". But i have mentioned the cookiepolicy.

Using Bing maps REST from Angular failing even though 200 response returned

I'm trying to use the Bing maps REST api from within angular. Fiddler shows a 200 response for both requests below, but Angular fails both, the $hhtp with "No Access-Control-Allow-Origin header is present' and the $request with "Unexpected token : "
I've not tried to do a cross-origin request with angular before but clearly I'm missing something. Any help would be appreciated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular-resource.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="myctrl"></div>
<script type="text/javascript">
var myapp = angular.module('myapp', ['ngResource']).config(['$httpProvider', function ($httpProvider) {
// delete header from client:
// http://stackoverflow.com/questions/17289195/angularjs-post-data-to-external-rest-api
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
myapp.controller('myctrl', ["$scope", "$resource", "$http", function ($scope, $resource, $http) {
var t = $resource('http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&key=MAPKEY&o=json',
{
callback: 'JSON_CALLBACK'
}, {
jsonpquery: { method: 'JSONP', isArray: false }
});
var x = t.jsonpquery().$promise;
debugger;
x.then(function (data) {
debugger;
console.log(data);
});
$http.get('http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&jsonp=jsonp&key=MAPKEY')
.success(function(data) {
debugger;
})
.error(function(data, status, error, thing) {
debugger;
console.log(data);
});
}]);
</script>
</body>
</html>
You'll need a map key from https://www.bingmapsportal.com/ to make a request though.
Any help appreciated, otherwise I'll drop down to using jQuery
Use $http.jsonp instead of $http.get. The following code works:
var url = "http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&jsonp=JSON_CALLBACK&key=YOUR_BING_MAPS_KEY";
$http.jsonp(url)
.success(function (data) {
debugger;
})
.error(function (data, status, error, thing) {
debugger;
console.log(data);
});

angularjs $resource Consuming domainservice error[Error: [ng:areq]] xxxx

**Does anyone know how you can check to see that a resource failed to be fetched in AngularJS?
error:
Error: [ng:areq]
http://errors.angularjs.org/undefined/ng/areq?p0=PhotoListCtrl&p1=not%20a%20function%2C%20got%20undefined
**
<html ng-app>
<head>
<title>angularjs</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body ng-controller="PhotoListCtrl">
<h1>Angular js</h1>
<p>Nothing here {{'yet' + '!'}}</p>
<button title="list" ng-click="list()">list</button>
<button title="copy" ng-click="copy()" >copy</button>
<ul >
<li ng-repeat="photo in photos">
<img src="{{'data:image/png;base64,' + photo.Image}}" title="{{photo.Name}}"></img>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular-resource.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular-route.min.js"></script>
<script type="text/javascript">
var app= angular.module('myApp', ['ngResource']).factory('dataservice', function ($resource) {
return $resource('/applicationdata.svc/Photos/:id', {id:'#id'}, {
query: { method: 'GET', isArray: true },
get: { method: 'GET', params: {id:0} },
remove: { method: 'DELETE' },
edit: { method: 'PUT' },
add: { method: 'POST' }
});
});
app.controller('PhotoListCtrl', ['$scope', 'dataservice', function ($scope, dataservice) {
$scope.photos = [];
$scope.list = function () {
dataservice.query({}, function (data) {
$scope.photos = data.value;
});
};
}]);
//function PhotoListCtrl($scope ,$http) {
// $http.get('/applicationdata.svc/Photos').success(function (data) {
// $scope.photos = data.value;
// });
// $scope.orderProp = 'Name';
// $scope.copy = function () {
// $http.post('/applicationdata.svc/Photos', $scope.photos[0]).success(function (data) {
// console.log(data);
// });
// }
//}
</script>
</body>
</html>

Resources