Angular Service returning "undefined" - angularjs

So I am sure I am not using best practices, but, I'm just trying to get this to work. I'm making a note taking app, and for whatever reason, the service I created, returns undefined and I can't figure out why.
Here's the service:
angular.module('notesService', []).factory('Notes', ['$http', function($http){
return {
get : function(){
var notes = $http.get('/api/notes');
return notes;
}
}
}]);
And here is the controller:
angular.module('mainController', [])
.controller('mainController', function($scope, Notes){
console.log(Notes.get());
});
The controller is not producing anything on the page just yet, i'm still testing.
Here is what the service returns to my controller:
e {
$$state : {
status : 1,
value : {
config : Object,
data: Array[10]
}
}
}
This isn't the entire thing, but it is all the stuff I need for my purposes.
Whenever I access $$state.value it returns undefined and I have no idea why.

You have the service in an entirely different module. So you gotta inject notesService into angular.module('mainController', [notesService]).
You dont ideally need to add new module for each controller and services, you can have single module and add everything to it

$http return a promise see documentation for $http
Also there is no need of the empty array in the angular.module parameter [] this might be what causes the error see in console.
angular.module('notesService').factory('Notes', ['$http', function($http){
return {
get : function(){
return $http.get('/api/notes');
}
}
}]);
angular.module('mainController')
.controller('mainController', function($scope, Notes){
Notes.get().then(function(result){
console.log(result);
})
});

I created an application that will help you to learn the best practices, plus solve your current problem.
//--In app.module.js--//
angular.module('notesApp', []);
//-- In app.controller.js--//
angular.module('notesApp')
.controller('MainController', ['$scope', '$http', '$log', 'notesFactory',
function($scope, $http, $log, notesFactory) {
$scope.data = {};
notesFactory.getData('http://localhost:3000/api/notes', 'GET')
.then(function(response) {
$log.log(response.data);
}, function(error) {
$scope.data = error;
});
}
]);
//--In 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;
}
]);
<html ng-app='notesApp'>
<head>
<title>
Notes Application
</title>
</head>
<body>
<div ng-controller='MainController'>
<pre>{{ data | json}}</pre>
</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>
Check the console for the json object as shown in the screenshot

Related

How to use a json file with a single controller app in AngularJS

I don't know how to make a service for a json file and call this service in my controller.
I have one controller in my app,and so must remain.
Try to run this example via run code snippet blue button.
Basically, You need to declare that service, the require it via Angular.DI, lastly call the service method and wait for its result.
Hope it helps
angular
.module('test', [])
.constant('API' , 'https://jsonplaceholder.typicode.com')
.service('TestService', function(API, $http) {
this.getData = function() {
return $http
.get(API + '/photos')
.then(function(response) {
return response.data;
})
};
})
.controller('TestCtrl', function($scope, TestService) {
//But a Resolve is preferred
TestService
.getData()
.then(function(data) {
$scope.album = data;
})
;
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<div ng-repeat="photo in album">
<h3 ng-bind="photo.title"></h3>
<img ng-src="{{photo.thumbnailUrl}}" />
</div>
</article>
</section>
You have to call your service from your controller.
your service:
angular.module('YOURAPP')
.service("userAService", function ($http) {
this.promise= function () {
return $http.get('resources/json/data.json')
}
});
And then in your controller function:
mycontroller = function(userAService){
userAService.promise().then(
function(response){
//do what you want in your promise
// try console.log(response.data) to see if you get your data.
}
)
}

Trouble making a back end call through Angular service

I am newbie learning to make back end calls from my angular app's service, I am making the back end call from the angular's Service.
I am calling the function in the service from the controller.
The rest service I provided is not the actual service I am hitting, for some reasons I cannot disclose it. I am sure that the rest service I have is valid and is working, cause I was able to hit it though the controller, which is a bad way of doing it, so this is the reason i want to change the back end call to the service.
Below is my js file. Any help would be appreciated, please feel free to let me know if I am doing this wrong.
angular.module("myApp",[])
.controller("myCont", ['myService', function($http, myService){
var vm = this;
this.myUrl = "some rest service";
console.log("The controller");
vm.getDataInController = function() {
console.log("The function is called");
myService.getData(vm)
.success(function (custs) {
console.log("The data is obtained");
})
.error(function (error) {
console.log("some error occurred");
});
}
}])
.service('myService', ['$http', function ($http) {
this.getData = function (vm) {
console.log("control is in the service");
console.log(vm.myUrl);
$http({
type: 'GET',
url: vm.myUrl
// data is where we have the JSON returned in the form of OBJECT from the gis
}).then(function successCallback(response) {
console.log("the backend call worked");
}), function errorCallback(response) {
console.log("the backend call worked");
}
};
}])
;
My Html file is
<!DOCTYPE html>
<html >
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src = "angular-min.js"></script>
<script src = "sampleOneScript.js"></script>
</head>
<body ng-app = "myApp" ng-controller = "myCont as main">
{{main.myUrl}}
<br>
<button type = "button" ng-click = main.getDataInController()>Click me </button>
</body>
</html>
The error I got in the console.
TypeError: Cannot read property 'getData' of undefined
at vm.getDataInController (http://localhost:63342/exercise.weokspce/ng-repeat%20example/sampleOneScript.js:15:26)
at fn (eval at (http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:212:87), :4:275)
at f (http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:252:82)
at m.$eval (http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:132:366)
at m.$apply (http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:133:60)
at HTMLButtonElement. (http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:252:134)
at HTMLButtonElement.Hf.c (http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:35:137)
The problem may be that you are not injecting properly all the dependencies for "myCont". Try changing the line:
.controller("myCont", ['myService', function($http, myService){
with:
.controller("myCont", ['$http', 'myService', function($http, myService){
and see if that corrects things

How to make an external call to a rest service in another domain [duplicate]

Im trying to get data in a Json format from a remote WS using Angular and im having some trouble.
The data comes from the web service correctly but i cant use it inside the controller.
Why is that?
Angular Code:
var booksJson;
var app = angular.module('booksInventoryApp',[]);
// get data from the WS
app.run(function ($http) {
$http.get("https://SOME_API_PATH").success(function (data) {
booksJson = data;
console.log(data); //Working
});
});
app.controller('booksCtrl', function ($scope) {
$scope.data = booksJson;
console.log($scope.data); //NOT WORKING
});
HTML:
<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data">{{book.name}}</h2>
</section>
You should put your $http.get inside your controller.
Also, the web service returns an object not an array. So your ng-repeat should be something like this: book in data.books
Here is a working example:
var app = angular.module('booksInventoryApp', []);
app.controller('booksCtrl', function($scope, $http) {
$http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks")
.then(function(response) {
$scope.data = response.data;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data.books">{{book.name}}</h2>
</section>
</article>
Create the bookJSON as array, and push the elements instead of assignment. So
var bookJSON=[];
Inside $http.get do
data.forEach(function(item) { bookJSON.push(item); });
The second console log will show undefined because, the call is async. The assignment happens in future.
The run method does not guarantee, that the code is run before controller loads.
There are other ways too to solve this issue.
Avoid global variable. Look at $routeProvider resolve property.
Or implement a service to get this data as promise.
Instead of using a run block you can use your $http service inside the controller, then attach your data to the scope like normal. Just remember to inject the $http service into your controller.
app.controller('booksCtrl', function ($scope, $http) {
$http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks").success(function (data) {
$scope.booksJson = data;
});
});
<!DOCTYPE html>
<html>
<head>
<title>test your webservice</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
<section ng-controller="booksCtrl">
</section>
</article>
<script type="text/javascript">
var app = angular.module('booksInventoryApp', []);
app.controller('booksCtrl', function($scope, $http) {
//ResponseInvocationAgentRequestDTO
var jsonObject = {
"id":65,
"idUserSender": 5}
console.log("aaaaaaaaaaaaaaaaaaaa");
$http({
method: 'put',
url: 'yout URI' ,
data: jsonObject
})
.success(function(data,status){
console.log('all is good', data);
})
.error(function(data,status){
console.log('Erreur into url '+data);
});
});
</script>
</body>
</html>

Getting data from a web service with Angular.js

Im trying to get data in a Json format from a remote WS using Angular and im having some trouble.
The data comes from the web service correctly but i cant use it inside the controller.
Why is that?
Angular Code:
var booksJson;
var app = angular.module('booksInventoryApp',[]);
// get data from the WS
app.run(function ($http) {
$http.get("https://SOME_API_PATH").success(function (data) {
booksJson = data;
console.log(data); //Working
});
});
app.controller('booksCtrl', function ($scope) {
$scope.data = booksJson;
console.log($scope.data); //NOT WORKING
});
HTML:
<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data">{{book.name}}</h2>
</section>
You should put your $http.get inside your controller.
Also, the web service returns an object not an array. So your ng-repeat should be something like this: book in data.books
Here is a working example:
var app = angular.module('booksInventoryApp', []);
app.controller('booksCtrl', function($scope, $http) {
$http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks")
.then(function(response) {
$scope.data = response.data;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data.books">{{book.name}}</h2>
</section>
</article>
Create the bookJSON as array, and push the elements instead of assignment. So
var bookJSON=[];
Inside $http.get do
data.forEach(function(item) { bookJSON.push(item); });
The second console log will show undefined because, the call is async. The assignment happens in future.
The run method does not guarantee, that the code is run before controller loads.
There are other ways too to solve this issue.
Avoid global variable. Look at $routeProvider resolve property.
Or implement a service to get this data as promise.
Instead of using a run block you can use your $http service inside the controller, then attach your data to the scope like normal. Just remember to inject the $http service into your controller.
app.controller('booksCtrl', function ($scope, $http) {
$http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks").success(function (data) {
$scope.booksJson = data;
});
});
<!DOCTYPE html>
<html>
<head>
<title>test your webservice</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
<section ng-controller="booksCtrl">
</section>
</article>
<script type="text/javascript">
var app = angular.module('booksInventoryApp', []);
app.controller('booksCtrl', function($scope, $http) {
//ResponseInvocationAgentRequestDTO
var jsonObject = {
"id":65,
"idUserSender": 5}
console.log("aaaaaaaaaaaaaaaaaaaa");
$http({
method: 'put',
url: 'yout URI' ,
data: jsonObject
})
.success(function(data,status){
console.log('all is good', data);
})
.error(function(data,status){
console.log('Erreur into url '+data);
});
});
</script>
</body>
</html>

How can I make an HTTP request using Angular.js?

I'm trying to make an HTTP request to the Last.fm API using Angular.js but I can't get it to work. I have separated out my Angular js files and have compiled them into one single js file called scripts.js using Codekit. The order in which the files are compiled is:
angular.min.js
app.js
controllers.js
services.js
Here is what my files look like:
app.js
var app = angular.module('app', []);
controllers.js
app.controller('similarArtistsController', function($scope, similarArtistsService) {
$scope.artists = [];
similarArtistsService.getArtists().success(function(response) {
console.log(response);
});
});
services.js
app.factory('similarArtistsService', function($http) {
var similarArtists = {};
similarArtists.getArtists = function() {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.getSimilar&api_key=MYLASTFMAPIKEY&format=json&limit=5&artist=Tame+Impala'
});
}
return similarArtists;
});
index.html
<body>
<div ng-app="app">
<div ng-controller="similarArtistsController"></div>
</div>
<script src="/js/compiled/scripts.js"></script>
</body>
In my console I see "Error: [$injector:unpr]" which I've learned to mean that the controller cannot resolve a dependency. In my case I believe it has something to with my service I'm injecting, but I don't know where the error lies.
Does compiling the scripts minify them too? If so, you need to declare your dependencies in an array...
app.controller('similarArtistsController', ['$scope', 'similarArtistsService', function($scope, similarArtistsService) {
$scope.artists = [];
similarArtistsService.getArtists().success(function(response) {
console.log(response);
});
}]);
app.factory('similarArtistsService', ['$http', function($http) {
var similarArtists = {};
similarArtists.getArtists = function() {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.getSimilar&api_key=MYLASTFMAPIKEY&format=json&limit=5'
});
}
return similarArtists;
}]);
Without that, Angular uses parameter names to resolve dependencies. Many minifiers mangle those names.
Include your services before your controllers so the service is known at time of injection
Can you try switching to app.service('similarArtistsService', function($http) {}); since this will return the function instance as opposed to factory which will return the value.
When you declare your dependencies in AngularJS, don't close off the array until after the function. See square brackets of array:
controllers.js
app.controller('similarArtistsController', ['$scope', 'similarArtistsService', function($scope, similarArtistsService) {
// code in here
}]);
services.js
app.factory('similarArtistsService', ['$http', function($http) {
// code in here
}]);

Resources