So I have my angular javascript as
var app = angular.module('app', []);
app.controller('controller', function($scope, $http) {
$http.get('http://localhost:8080/core/students.json')
.success(function(data) {
$scope.user = data;
});
});
and my rest controller with
#RestController
public class StudentRestController {
#RequestMapping(value = "/students", produces = { "application/json" }, method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public Student getStudent() {
// return studentService.getStudentByUserName(userName);
Student s = new Student();
s.setUserName("userName");
s.setEmailAddress("email");
return s;
}
}
but for some reason, the javascript ajax request isn't hitting the method getStudent(). Why is this? I get a console error
"GET http://localhost:8080/core/students.json 404 (Not Found)"
ordinary button url calls work as expected
change angularjs app as
var app = angular.module('app', []);
app.controller('controller', [ "$scope", "$http", function($scope, $http) {
$http.get("http://localhost:8080/students").success(function(data) {
$scope.user = data;
});
} ]);
that holds if ur web.xml
<servlet-mapping>
<servlet-name> dispatcherServlet </servlet-name>
<url-pattern> * </url-pattern>
</servlet-mapping>
You are defining "/students" on the #RequestMapping, then your URL should be ".../core/students".
Related
I set up a AMSX Web Service and it works properly when accessing the URL:
public class ExpenseService : System.Web.Services.WebService
{
[WebMethod]
public void Get()
{
List<Expense> expenses = new List<Expense>();
expenses.Add(new Expense(1, "Netflix", "Netflix", 20.00, new DateTime()));
expenses.Add(new Expense(2, "Spotify", "Spotify", 14.90, new DateTime()));
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(expenses));
}
}
However, when I make a GET from my AngularJS controller through $http:
var app = angular.module("app", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider.when("/home", {
templateUrl: "Pages/Home.html",
controller: "homeController"
})
});
app.controller("homeController", function ($http) {
var self = this;
$http.get("ExpenseService.asmx/Get")
.then(function (response) {
self.expenses = response.data;
})
});
I receive this error on console:
And if I click on the link from the error message (underlined on image above), I got the error on page as well:
Just to remember: I can access the JSON when entering URL manually on browser.
[System.Web.Script.Services.ScriptService]//add it and try again
public class ExpenseService : System.Web.Services.WebService
I'm trying to do the following.
Angular controller calls and MVC controller GET method. This method then calls into a REST API on the web which returns a list of configuration items. I then turn this into a dictionary so I can look up configuration values based on the key, and then I want to pass this back to the Angular controller and store it there in a variable that I can access from many different scenarios, eg displaying them in grids, updating values, changing and updating them back to the REST API etc. I have tried to set up the pipes but I can't seem to get the data in a readable/usable format in the Angular controller.
My controller
app.controller("SEFlexHomeController", ["$scope", "$http", "$modal", "$log", "$element", "$rootScope", "AlertsService", "AuthService", "SEApplicationService", function ($scope, $http, $modal, $log, $element, $rootScope, AlertsService, AuthService, SEApplicationService) {
$rootScope.closeAlert = AlertsService.closeAlert;
$scope.isDataLoading = false;
$scope.AuthService = AuthService;
$scope.configvalues = angular.fromJson(SEApplicationService.getCloudConfigParams());
}
]);
My Angular Service
app.factory("SEApplicationService", ["$log", "$http", "$timeout", function($log, $http, $timeout) {
var appService = {};
appService.getCloudConfigParams = function () {
return $http.get("/SEFlex/SEFlexAdmin/GetCloudConfigValues");
}
return appService;
}]);
My MVC controller
public ActionResult GetCloudConfigValues()
{
try
{
var helper = new ApplicationServiceHelper();
var dictionary = helper.GetCloudConfigValues()
.ToList()
.ToDictionary(item => item.ConfigKey, item => item.ConfigValue);
var returnData = JsonConvert.SerializeObject(dictionary);
return Json(new
{
success = true,
data = returnData
}, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
return Json(new
{
success = false,
errors = new[] { exception.Message }
});
}
}
I can confirm at the time of creating the Dictionary in the MVC controller, the dictionary looks as expected for a .NET dictionary. What do I need to do to convert this either before transmission back or back in Angular, so that I can access it in angular as
$scope.configvalues["keyName"]
The $http.get() call returns a promise. You should change the
$scope.configvalues = angular.fromJson(SEApplicationService.getCloudConfigParams());
to
SEApplicationService.getCloudConfigParams().then(function(config) {
$scope.configvalues = config;
});
Here is my view:
<div>
<select ng-model="firstSupplier" ng-options="firstSupplier as firstSupplier.SupplierName for firstSupplier in jsonSuppliers"></select>
</div>
and here is my angular controller:
(function() {
var app = angular.module("CustCMS");
var indexController = function($scope, $http) {
$http.get("/Home/GetAllSuppliers")
.then(function (response) {
$scope.jsonSuppliers = response.data;
$scope.firstSupplier = $scope.jsonSuppliers[0];
});
};
app.controller("IndexController", ["$scope", "$http", indexController]);
}());
and here is my mvc controller:
public JsonResult GetAllSuppliers()
{
var suppliers = GetAll();
return Json(new { data = suppliers}, JsonRequestBehavior.AllowGet);
}
here is the json that returns to the angular controller jsonSuppliers:
{"data":[{"SupplierId":1,"SupplierName":"Normstahl","PrefixCountryCode":"NS01COUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":2,"SupplierName":"TestSupplier 2","PrefixCountryCode":null,"UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":3,"SupplierName":"Ditec","PrefixCountryCode":"DIIT01COUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":4,"SupplierName":"Ospf","PrefixCountryCode":"CRCOUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":5,"SupplierName":"Alsta","PrefixCountryCode":null,"UseOrderSystem":false,"IsDirect":false,"Customers":[]}]}
Is where something that im missing here?
I don't get any errors in the console....
Is there an easier way to do it that would be much appreciated!
I'm an angular newby. I'm hoping to pass params to a service that fetches data form a server depending on those params.
for example, if I want to pass a book name string and then use it in the service to concatenate with the request url. The documentation does not show clearly in this subject and I could not find helpful examples in other resources.
Let say, this is the controller:
app.controller('BookController', ['$scope', '$routeParams', 'books', function($scope, $routeParams, books) {
// sending params to books service before a successful return
books.success(function(data) {
$scope.book = data[$routeParams.bookId];
});
and this is the service
app.factory('books', ['$http', function($http) {
// var url = 'http://...' + ParamFromController + '.json'
return $http.get(url)
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
So, how can I send params to 'books' service and then use it in the service?
Thanks a lot in advance.
You can declare your service as:
app.factory('books', ['$http', function($http) {
// var url = 'http://...' + ParamFromController + '.json'
return {
getVal: function(url,options){
return $http.get(url,options)
}
}
}]);
and use it in your controller and provide appropriate params to pass into 'books' service:
app.controller('BookController', ['$scope', '$routeParams', 'books', function($scope, $routeParams, books) {
// sending params to books service before a successful return
books.getVal('api/activity.json',{'name':'abc'}).success(function(data) {
$scope.book = data[$routeParams.bookId];
});
Also, dont use the .success() callback both in your service and controller function. The books service is returning a promise($http returns a promise implicitly) and you can handle that in controller.
Right now you are returning the promise / result of the $http as the service instance.
Services are not meant to work this way. You should return an object that holds several properties / methods that define your service:
app.factory('books', ['$http', function($http) {
var instance = {
getBook: function(bookId) {
return $http.get(...);
}
}
return instance;
}
In the controller you can then use the books service as follows:
books
.getBook($routeParams.bookId)
.then(function (result) { ... });
app.factory('books', ['$http', function($http) {
var booksService = {};
booksService.getBook = function(bookId){
{
return $http.get(url, bookId);
};
return booksService;
}]);
and in your controller
app.controller('BookController', ['$scope', '$routeParams', 'books', function($scope, $routeParams, books) {
books.getBook($routeParams.bookId).success(function(data) {
$scope.book = data;
});
I'm working on a mobile app using AngularJS as a framework, currently I have a structure similar to this:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'homeCtrl'
})
.when('/one', {
templateUrl : 'pages/one.html',
controller : 'oneCtrl'
})
.when('/two', {
templateUrl : 'pages/two.html',
controller : 'twoCtrl'
});
}]);
app.controller('homeCtrl', ['$scope', function($scope) {
}]);
app.controller('oneCtrl', ['$scope', function($scope) {
}]);
app.controller('twoCtrl', ['$scope', function($scope) {
}]);
And then I'm displaying the content with an ng-view:
<div class="ng-view></div>
Things are working well but I need to load data from a JSON file to populate all the content of the app. What I want is to make and an AJAX call only once and then pass the data through all my different controllers. In my first attempt, I thought to create a Service with an $http.get() inside of it and include that in every controller, but it does not work because it makes a different ajax request everytime I inject and use the service. Since I'm new using angular I'm wondering what is the best way or the more "angular way" to achieve this without messing it up.
Edit: I'm adding the code of the service, which is just a simple $http.get request:
app.service('Data', ['$http', function($http) {
this.get = function() {
$http.get('data.json')
.success(function(result) {
return result;
})
}
});
Initialize the promise once, and return a reference to it:
No need to initialize another promise. $http returns one.
Just tack a .then() call on your promise to modify the result
angular.module('app', [])
.service('service', function($http){
this.promise = null;
function makeRequest() {
return $http.get('http://jsonplaceholder.typicode.com/posts/1')
.then(function(resp){
return resp.data;
});
}
this.getPromise = function(update){
if (update || !this.promise) {
this.promise = makeRequest();
}
return this.promise;
}
})
Codepen example
Edit: you may consider using $http cache instead. It can achieve the same results. From the docs:
If multiple identical requests are made using the same cache, which is not yet populated, one request will be made to the server and remaining requests will return the same response.
Try this to get JSON Data from a GET Link:
(function (app) {
'use strict';
app.factory('myService', MyService);
MyService.$inject = ['$q', '$http'];
function MyService($q, $http) {
var data;
var service = {
getData: getData
};
return service;
//////////////////////////////////////
function getData(refresh) {
if (refresh || !data) {
return $http.get('your_source').then(function(data){
this.data = data;
return data;
})
}
else {
var deferrer = $q.defer();
deferrer.resolve(data);
return deferrer.promise;
}
}
}
}(angular.module('app')));
Now you can add this dependency in your controller file and use:
myService.getData().then(function(data){
//use data here
}, function(err){
//Handle error here
});