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>
Related
I have an Angular controller that gets data via a service from 2 different json files, and I need to pass that data to a view.
The controller file:
.controller('MainController', ['info', function (info){
var vm = this;
info.getAddresses().then(function(data) {
vm.addresses = data.addresses;
});
info.getNames().then(function(data) {
vm.names = data.names;
});
console.log(this);
}])
The getAddresses and getNames functions are just $.get('json-url').
If I use console.log(this) in the controller just before the closing bracket, I can see in the console the data below:
but I cannot access that 2 properties from the view. Am I missing something?
It's probably a digest cycle issue. Adding $scope.$apply would fix the issue.
$.get() from jQuery alter the value of vm.names but it's not part of the Angular digest cycle.
Here is a working example, hope this helps
angular.module('myApp', [])
.factory('info', function() {
var mock = function() {
return new Promise(function(resolve, reject) {
resolve({
"names": ['Alice', 'Bob']
});
});
};
return {
getNames: mock
};
})
.controller('MainController', function(info,$scope) {
var vm = this;
info.getNames().then(function(data) {
vm.names = data.names;
// trigger $apply manually
$scope.$apply();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainController as vm">
{{vm.names}}
</div>
</div>
use scope variable to store the data instead of var
.controller('MainController', ['info', '$scope', $scope, function (info){
$scope.vm = this;
info.getAddresses().then(function(data) {
$scope.vm.addresses = data.addresses;
});
info.getNames().then(function(data) {
$scope.vm.names = data.names;
});
console.log(this);
}])
and call this scope variable in your view like
<tr ng-repeat = item in vm>
<td>you can get your data here</td>
</tr>
Hope this works
You are assigning your data to a variable and not to the $scope.
Your controller should be like this
.controller('MainController', ['info', '$scope', function (info, $scope){
info.getAddresses().then(function(data) {
$scope.addresses = data.addresses;
});
info.getNames().then(function(data) {
$scope.names = data.names;
});
console.log($scope);
}])
Here you have used controller as syntax. So you need to use it into ng-controller. Check below code.
<div ng-controller="MainController as vm">
<div ng-repeat="vm.addresses in address">{{ address }}</div>
<div ng-repeat="vm.names in name">{{ name}}</div>
</div>
If address or name is json object then you need to use specific key within address or name object.
For Angular 2+
Hold the json response in some variable:
public data:any=your json response;
And then in view, display it vi using *ngFor directive:
<p *ngFor="let d of data">{{d}}</p>
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
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.
}
)
}
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
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>