Angular response is undefined - angularjs

Trying to retrieve using angular the json found at: "https://api.github.com/users/angular", more precisely the id property from that json.
Any thoughts on why this fails (in debug mode I get a
'response is not defined'
):
<html ng-app="myViewer">
<head>
<script data-require="angular.js#*" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
</head>
<body ng-controller="MyController">
{{ result.id }}
{{ err }}
</body>
<script type="text/javascript">
(function() {
var app = angular.module("myViewer", []);
var MyController = function($scope, $http)
{
$http.get("https://api.github.com/users/angular")
.then(function1, onerr);
var function1 = function(response)
{
$scope.result = response.data;
}
var onerr = function(reason)
{
$scope.err = "nightmare";
}
}
app.controller("MyController", ["$scope", "$http", MyController]);
}());
</script>
</html>
I expect the result to be the id that you can see by copying that link in your browser.

Here is a working fiddler https://jsfiddle.net/paka2/8roj37q9/1/
angular.module("myViewer", []).controller("myCtrl", function($scope,$http){
this.result = {};
this.err ;
$http.get("https://api.github.com/users/angular")
.then(function1, onerr) ;
function function1 (response)
{
$scope.result = response.data;
}
function onerr (reason)
{
$scope.err = "nightmare";
}
});
Hope it helps!!

Works if I correct the order:
var function1 = function(response)
{
$scope.result = response.data;
}
var onerr = function(reason)
{
$scope.err = "nightmare";
}
$http.get("https://api.github.com/users/angular")
.then(function1, onerr);
function1 should be defined before i call it with then.

I think your promise is wrong.
$http.get('https://api.github.com/users/angular').then(function(response){
$scope.result = response.data;
})
See same HTTP call working below:
https://plnkr.co/edit/8JqZ5NukHnHWGPxZ0GRr

try this i think you have incorrectly defined the controller as mycontroller and it should be SecondController instead.
app.controller("MyController", ["$scope", "$http", SecondController ]);

Try with following
var function1 = function(response) { $scope.result = response; }

Related

Angular Js is not working properly

angular js not displaying anything even like simple expressions. i am tying to execute below code but no hope. can anyone help me out.
below code is for view to display.
`<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="/../../Scripts/angularsample.js"></script>
</head>
<body ng-app="spiceApp">
<div>
<div ng-controller="SpicyController">
<p> lets try some code by using service </p>
<input ng-init="message='Girish'" ng-model="message" />
<button ng-click="notify(message);">Notify{{1+2}}</button>
<p>alert will display only by clicking three times.</p>
</div>
<div ng-controller="List">
<button ng-click="bringList()">getList</button>
<table>
<tr ng-repeat="app in appslist">
<td>
{{app.Name}}
</td>
</tr>
</table>
</div>
</div>
</body>
</html>`
js code
var myApp = angular.module('spiceApp', []);
myApp.controller('SpicyController', ['$scope', '$http', 'userService', , function ($scope, $http, userService) {
//below code is using sservice
$scope.notify = function (msg) {
userService(msg);
};
}]);
myApp.controller('List', ['$scope', 'getList', function ($scope, getList) {
$scope.bringList = function () {
getList.getAppsList().then(function (list) {
$scope.appslist = list;
});
};
}]);
myApp.factory('getList', ['$http',function ($http) {
//this code for getting list from controller.
return getList.getAppsList=function(){
$http({
method: 'GET',
url: 'Home/GetAppsList'
})
.success(function (response) {
return response.data;
}, function (error) {
console.log(error);
});
}
}]);
myApp.factory('userService', ['$window', function (win) {
var msgs = [];
return function (msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join('\n'));
msgs = [];
}
};
}]);`
please tell me where i am wrong. nothing is working. expression is displaying like {{1+2}} in the ouptut.
You have a typo here:
myApp.controller('SpicyController', ['$scope', '$http', 'userService', , function
with the 2 comas so the dependancies are messed up.
i tried in different way with same view but i modified the js file now it's working fine.
var myApp = angular.module('spiceApp', []);
myApp.controller('SpicyController', ['$scope', '$http', 'userService',function ($scope, $http, userService) {
//below code is using sservice
$scope.notify = function (msg) {
userService(msg);
};
}]);
myApp.factory('userService', ['$window', function (win) {
var msgs = [];
return function (msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join('\n'));
msgs = [];
}
};
}]);
myApp.controller('List', ['$scope', 'getList', function ($scope, getList) {
$scope.bringList = function () {
getList.getAppsList.then(function (data) {
$scope.appslist = data;
});
};
}]);
var getList = angular.module("spiceApp").factory("getList", ['$http', function ($http, getList) {
return {
getAppsList: (function (response) {
return $http({
method: 'GET',
url: 'GetAppsList'
})
.then(function (response) {
console.log("coming from servicejs", response.data);
//return data when promise resolved
//that would help you to continue promise chain.
return response.data;
});
})()
};
return getList;
}]);

Multiple http.get in service

I wanna use multiple ( in this case, 2 ) $http.gets in my service !
As you know the simple form of using $http.get is this :
app.factory('MyService', function ($http, $q) {
return {
getData: function() {
return $http.get('myfile.json')
.then(function(response) {
return response.data;
});
}
};
});
Now I wanna use 2 files ( 2 $http.gets ) and compare them to each other ( with some for loops and etc that I can ... ) !
What can I do now ? :(
use $q.all.
Add $q to controller's dependencies, exemple
$scope.req1 = $http.get('myfile.json');
$scope.req2 = $http.get('myfile2.json');
$q.all([$scope.req1, $scope.req2]).then(function(data) {
// data is array of your files
if ( JSON.stringify(data[0]) === JSON.stringify(data[1])){
console.log('is equal');
}
});
It is an extension of Hajji Tarik's solution. I was able to derive from your comments that you were still not clear with what to code in where. So I have developed a sample application which will assist you for the same.
//--app.module.js--//
angular.module('notesApp', []);
//--app.service.js--//
angular.module('notesApp')
.factory('notesFactory', ['$http',
function($http) {
var notesService = {};
notesService.getData = function(url, method) {
return $http({
url: url,
method: method
});
}
return notesService;
}
]);
//--app.controller.js--//
angular.module('notesApp')
.controller('MainController', ['$scope', '$http', '$log', '$q', 'notesFactory',
function($scope, $http, $log, $q, notesFactory) {
$scope.data = {};
var data1 = notesFactory.getData('http://localhost:3000/api/notes/1', 'GET');
var data2 = notesFactory.getData('http://localhost:3000/api/notes/2', 'GET');
var combinedData = $q.all({
firstResponse: data1,
secondResponse: data2
});
combinedData.then(function(response) {
$log.log(response.firstResponse.data);
$log.log(response.secondResponse.data);
//Write your comparison code here for comparing json results.
}, function(error) {
$scope.data = error;
});
}
]);
<html ng-app='notesApp'>
<head>
<title>
Notes Application
</title>
</head>
<body>
<div ng-controller='MainController'>
</div>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js'></script>
<script src='app.module.js'></script>
<script src='app.controller.js'></script>
<script src='app.service.js'></script>
</body>
</html>

$http.get(url) not returning data

I am building a service in angular and injecting the service in controller. I am trying to fetch data from json file and am using $http. however the data is not getting returned and i get undefined.
I am updating my code as per suggestion by #Phil
Service.js
;(function(app) {
app.factory('authService', ['$log', '$http','$location', function($log, $http,$location) {
var url = 'js/user.json';
var authService= {};
var userExist=null;
authService.authenticate = function(userid) {
var userobj = $http.get(url).success(function (data) {
userExist = data
console.log(data);
return userExist;
$log.info("Loaded users");
})
.error(function (error) {
$log.info(error);
$log.info("No user exists");
return error;
})
return userobj;
}
return authService;
}]);
})(angular.module('userApp'));
Controller.js
;(function(app) {
app.controller('Controller', ['$scope', '$log','$location','authService', function($scope,$log,$location,authService) {
$scope.data={};
$scope.getUsers = function()
{
userid = "123";
$scope.data = authService.authenticate(userid);
console.log($scope.data);
return $scope.data ;
}
}])
}(angular.module('userApp')));
index.html
<div class="main" ng-controller="Controller">
<input type="button" name="btngetusers" ng-click="getUsers()"></input>
</div>
<script src ="js/app.js"> </script>
<script src ="js/controller/Controller.js"> </script>
<script src ="js/services/Service.js"> </script>
user.json
i have placed the json file under the js directory.
[
{
"UserId": "1",
"FName": "Hice",
"LastName": "Harry"
},
{
"UserId": "2",
"FName": "Andrew",
"LastName": "Ads"
}
]
The data is getting returned as undefined. what am i missing here?
UPDATED CODE
I am updating my code as per suggestion by #skubsi
Service.js
;(function(app) {
app.factory('authService', ['$log', '$http','$location', function($log, $http,$location) {
var url = 'js/user.json';
var authService = {};
var userExist=null;
authService.authenticate = function(userid,success,error) {
$http.get(url).success(function(data){
success(data);
})
.error(error);
};
return authService;
}]);
})(angular.module('userApp'));
Controller.js
;(function(app) {
app.controller('MainController', ['$scope', '$log','$location','authService', function($scope,$log,$location,authService) {
var self = this;
this.data = null;
this.getUsers = function(){
function success(response){
self.data = response;
}
function error(){
console.log("error");
}
authService.authenticate(1,success,error);
}
}])
}(angular.module('userApp')));
index.html
<div class="main" ng-controller="MainController as main">
{{main.data}}
<input type="button" name="btngetusers" value ="Get User" ng-click="main.getUsers()"></input>
</div>
<script src ="js/app.js"> </script>
<script src ="js/controller/MainController.js"> </script>
<script src ="js/services/authenticate.js"> </script>
First things first: your JSON is invalid, you can verify this yourself by entering the JSON you supplied in JSONLint.
Parse error on line 2:
[ { UserId: 123,
--------------^
Expecting 'STRING', '}'
Secondly you pass a unknown service into your controller:
authenService
Then you should realize a promise is code that will run asynchronously, meaning that:
userid = "123";
$scope.data = authService.authenticate(userid);
console.log($scope.data);
return $scope.data ;
will not run synchronously. console.log($scope.data); Will be executed long before your authenticate method will be done. So you need to find a way to make your controller handle accordingly whilst keeping concerns separated. (and not falling into a deferred-anti-pattern).
You could for example add additional parameters to your authenticate function, which will enable the function to call back the original caller.
authService.authenticate = function(userid, success, error) { //success and error are functions
$http.get(url).success(function(data) {
//separation of concerns:
//execute logic.. set flags, filter w/e belongs to your authentication process.
success(data);
})
.error(error); //no processing required
};
So that in your controller all that is left to do is calling the authService and providing it a way to set your data:
this.getUsers = function() {
//This will enable to set the response to your controllers data model.
function success(response) {
self.data = response;
window.alert(response);
}
function error() {
window.alert('shite happened');
}
authService.authenticate(1, success, error);
};
Note that I have used the controllerAs syntax instead of $scope. To prove this mechanism works I created a plunker for you to investigate.
Your authenticationService.authenticate method doesn't return anything.
Specifically, the service name is authService and you're calling authenticationService.authenticate.

Multiple Http request in single controller

var nameSpace = angular.module("MyTutorialApp", []);
nameSpace.controller("MainController", ['$scope', '$http',
function($scope, $http)
{
$http.get("../api/api.php?fxn=" + encodeURIComponent("getCategories") +
"&jsn=" + encodeURIComponent("{'code':'1'}"))
.success(function(response)
{
$scope.names = response;
});
$scope.myData = {};
nameSpace.controller("MainController", ['$scope', '$http',
$scope.myData.doClick = function($event, name, $scope, $http,$config)
{
alert(name);
var element = name;
console.log(element);
$http.get("../api/api.php?fxn=" + encodeURIComponent("getSubCategories") +
"&jsn=" + encodeURIComponent("{'code':'element'}"))
.success(function(response)
{
$scope.subCat = response;
});
}]);
}
]);
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="js/maincontroller.js"></script>
</head>
<body ng-app="MyTutorialApp" >
<div ng-controller="MainController">
<table class="table">
<tr class="row1" ng-repeat="list in names.category">
<td ng-click="myData.doClick($event,list.name)">{{ list.name }}</td>
</tr>
</table>
</div>
</body>
</html>
Hi, i m not able to make the second http request , It says get property undefined. I tried for quite along time, i am not able to spot what is going wrong. Kindly Help me. I am just starting to use angular.
To explain what I am trying to achieve , the first http request calls for the list of categories , the list is populated and after that on click of any of the category , the category is sent as the jsn for the second http request . And it fetch's the sub category
Check this
// Code goes here
var nameSpace = angular.module("MyTutorialApp", []);
nameSpace.factory('factoryRefrence', ['$http', '$q',
function($http, $q) {
return {
getCategories: function() {
var deferred = $q.defer();
$http.get("../api/api.php?fxn=" + encodeURIComponent("getCategories") +
"&jsn=" + encodeURIComponent("{'code':'1'}"))
.success(function(response) {
deferred.resolve(response);
});
return deferred.promise;
},
getsubCategories: function(element) {
var deferred = $q.defer();
$http.get("../api/api.php?fxn=" + encodeURIComponent("getSubCategories") +
"&jsn=" + encodeURIComponent({
'code': element
}))
.success(function(response) {
deferred.resolve(response);
});
return deferred.promise;
}
}
}
]);
nameSpace.controller("MainController", ['$scope', '$http', 'factoryRefrence',
function($scope, $http, factoryRefrence) {
factoryRefrence.getCategories().then(function(response) {
$scope.names = response;
});
$scope.myData = {};
$scope.myData.doClick = function(event, name) {
alert(name);
var element = name;
console.log(element);
factoryRefrence.getsubCategories().then(function(response) {
$scope.subCat = response;
});
}
}
]);
Demo
this is the way to communicate with functions in factory. if you setup like this it should work fine. and besides in your code you are defining controller twice which is not okay.

How to change the contents of an AngularJS view at runtime?

Inside an AngularJS controller I do a $http.post() request and update $scope with new data which works fine.
But in case of an error, I want to change the template of the same controller to another one. I haven't figured out how to change the template of a controller.
Here is some pseudo code inside the controller:
// this is the controller
var self = this
$http
.post('/something', $scope.something)
.success(function(data) {
$scope.result = data
})
.error(function(err) {
$scope.error = err
var statusCode = err.statusCode
// for example on a 403, I want the template 'errors/403.html' to
// be rendered
self.template = $templateCache.get('errors/' + statusCode + '.html')
})
Any ideas how this is possible? I do not want to put '/errors/403' to the routing because it is not idempotent.
Thanks for any suggestions. I am a bit desperate here ...
try like
$location.path('/login');
first of all you should setup the route provider and use then use $location service to change the URL.
configure route provider :
var app = angular.module("myApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider.when("/error", { controller: "", templateUrl: "/app/error.html" });
// setup some more routes here as above
$routeProvider.otherwise({ redirectTo: "/login" });
And in JS file -
var self = this
$http
.post('/something', $scope.something)
.success(function(data) {
$scope.result = data
})
.error(function(err) {
$scope.error = err
var statusCode = err.statusCode
// for example on a 403, I want the template 'errors/403.html' to
// be rendered
$location.path("/error");
})
Don't forget to add the angular-route.js file.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body data-ng-app="myApp">
<div data-ng-view=""></div>
<script src="Scripts/angular-route.js"></script>
</body>
</html>
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "./index.html";
return;
}
// otherwise
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);

Resources