Workout on restful services for single page applications - angularjs

I am just a beginner in Angularjs. I have been trying for consuming WebApi service by angularjs. I am following this
1: http://weblogs.asp.net/dwahlin/using-an-angularjs-factory-to-interact-with-a-restful-service documentation. It has been clearly documented about use of factories and services. I want to perform crud operations and I am following the same way but I am not even getting the methods called in the Api controller and how can I get the data to be listed in the view?
I have done this: My factory is defined in index.cshtml
In the Main view ie. Index.cshtml
#{
ViewBag.Title = "Index";
}
<style>
.container {
float: left;
width: 100%;
}
</style>
<script src="~/Scripts/angular.min.js"></script>
<h2>Practising Angular</h2>
List
Edit
<div ng-app="demoApp">
<div class="container">
<div ng-view=""></div>
</div>
</div>
<script>
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', { controller: 'SimpleController', templateUrl: 'Home/List' })
.when('/Edit', { controller: 'SimpleController', templateUrl: 'Home/Edit' })
.otherwise({ redirectTo: '/' });
});
demoApp.factory('dataFactory', ['$http', function ($http) {
var urlBase = '/api/Customer';
var dataFactory = {};
dataFactory.getCustomers = function () {
return $http.get(urlBase);
};
dataFactory.getCustomer = function (id) {
return $http.get(urlBase + '/' + id);
};
return dataFactory;
}]);
demoApp.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
$scope.customers;
getCustomers();
function getCustomers() {
dataFactory.getCustomers()
.success(function (custs) {
$scope.customers = custs;
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
}]);
</script>
I have this controller which runs by default as it is an MVC 4.0 project and "Home Controller" and "Index" is defined in the route.
namespace Routing_Angular.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult List()
{
return PartialView();
}
public ActionResult Edit()
{
return PartialView();
}
}
}
The List and Edit Action methods are returned as partialviews because they will act as views to render data in angular js.
So, this is what I have in both of the partial views..
List.cshtml
#{
ViewBag.Title = "List";
}
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="filter.name" />
<ul>
<li ng-repeat="objCust in customers | filter:filter.name">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
Customer Name:<br />
<input type="text" ng-model="newCustomer.name" /><br />
Customer city:<br />
<input type="text" ng-model="newCustomer.city" /><br />
<button ng-click="addCustomer()">Add customer</button>
</div>
Edit.cshtml
#{
ViewBag.Title = "Edit";
}
<h2>Edit the particular user. Things are under construction</h2>
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="city" />
<ul>
<li ng-repeat="objCust in customers | filter:city">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
</div>
This is the Api controller/Service that is being getting called from Factory in the index.cshtml. But none of the methods are getting called. How the data got from the factory objects will be shown in the View?
ApiController
namespace Routing_Angular.Controllers
{
public class CustomerController : ApiController
{
//
// GET: /Customer/
public HttpResponseMessage Get()
{
CustomerService ObjService = new CustomerService();
var Clients = ObjService.GetClients();
if (Clients.Count < 1) throw new HttpResponseException(HttpStatusCode.NotFound);
return Request.CreateResponse<IEnumerable<tblreferralService>>(HttpStatusCode.OK, Clients);
}
// GET api/customers/5
public HttpResponseMessage Get(int id)
{
CustomerService ObjService = new CustomerService();
var Client = ObjService.GetClient(id);
if (Client == null) throw new HttpResponseException(HttpStatusCode.NotFound);
return Request.CreateResponse<tblreferralService>(HttpStatusCode.OK, Client);
}
}
}
Below I am attaching the image for project structure. It is just a basic structure.

Related

I can't connect to the database with angularjs and spring boot mvc

I'm trying to integrate AngularJS in my Spring Boot MVC project but I can't understand how to connect it to Spring Boot through #RequestMapping and #GetMapping.
When I get the project locally I don't detect any error on chrome Google Developer Tools.
This is my Controller
var main = angular.module('main', []);
main.component('main', {
templateUrl: 'views/main.template.jsp',
});
main.controller('CaseJson', function($scope, $http) {
$http.get('caseprod/all')
.then(function(response, status) {
$scope.myWelcome = response.data;
}, function(err) {
console.error("Error", err);
});
});
main.controller('getcontroller', function($scope, $http, $location) {
$scope.getfunction = function(){
var url = $location.absUrl() + "caseprod/all";
$http.get(url).then(function (response) {
$scope.response = response.data
}, function error(response) {
$scope.postResultMessage = "Error with status: " + response.statusText;
});
}
})
I tried with both controllers
And this is where it should display:
<div data-ng-controller="getcontroller">
<div var="current" data-ng-repeat="case in response">
<div class="container">
<div class="img-container">
<img data-ng-src="{{data.img}}" alt="">
</div>
<div class="user-info">
<h2>"{{data.nome}}"</h2>
<span>"{{data.annoFondazione}}"</span>
</div>
</div>
</div>
</div>
Here the controller spring
#RestController
#RequestMapping("/caseprod")
public class CaseProduttriciController {
#Autowired
private CaseProduttriciService caseprodservice;
#GetMapping(value = "/all", produces = MediaType.APPLICATION_JSON_VALUE)
public List<CaseProduttrici> findAll(){
return caseprodservice.findAll();
}
If you need something else, tell me. Thanks
spring.datasource.url=dbc:mysql
Is it normal that you miss "j" in jdbc ?
What are showing your logs ?

GET request in Angular

Hi guys I had used this code my AngularJS app to execute a GET request, now I want to use it in Angular I have some problems with update it can anyone help me ?
script :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://---:8080/api/v1/users")
.then(function(response) {
$scope.users = response.data;
$scope.AfficherMap = AfficherMap;
console.log(response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
html:
<div ng-controller="myCtrl" style="width: 250px;">
<div ng-repeat="user in users" ng-click="AfficherMap(user.id)">
<a>{{user.id}} {{user.firstName}} {{user.lastName}}</a>
</div>
</div>
You can do this in this way...
Make a get function in UserService:
constructor(http:HttpClient){}
getUsers(){
return this.http.get("api_url");
}
Now In your component call this function.
constructor(private userService: UserService){
}
ngOninit(){
this.userService.getUsers().subscribe((res)=>{
console.log(res); // This is your users list...
this.users = res;
});
}
Now In your html
<div style="width: 250px;">
<div *ngFor="let user of users">
<a (click)="AfficherMap(user.id)">{{user.id}} {{user.firstName}-
{{user.lastName}}
</a>
</div>
</div>
AngularJS(1.x) and Angular(2+) are totally different frameworks, in Angular(2+) you will need to use HttpClient module to do an HTTP call more details on the official doc
Find a suggestion for your code:
getUsers() {
this.api.getUsersCall()
.subscribe(users => {
for (const u of (users as any)) {
this.users.push({
name: u.name,
username: u.username
});
}
});
}
given that api is an instance of the APIService you need to create a module for it and declare it in your component class with the specifier private, APIService module will contains the definition of getUsersCall:
getUsersCall() {
return this.http.get("http://---:8080/api/v1/users");
}

mvc angularjs autocomplete

I am trying to implement textbox autocomplete functionality in MVC angularjs. I have see examples with angucomplete method but it gets all db values in one shot. When I hit the key back again it doesnt go to MVC controller action.
Below is my code view code:
<div ng-controller="sampleController">
<div ng-app="medAapp" ng-controller="sampleController">
<div angucomplete-alt id="txtautocomplete" placeholder="Type Country name" pause="100" selected-object="AfterSelectedCoutries" local-data="countries" search-fields="Country" title-field="Country" minlength="1" input-class="form-control" match-class="highlight">
</div>
<div ng-show="SelectedCountries">
Selected Country: {{SelectedCountries.Country}}
</div>
</div>
</div>
Module code:
var medApp = angular.module("medApp", ['angucomplete-alt', 'ui.grid', 'ui.grid.pagination', 'ui.grid.selection', 'ui.grid.exporter',
'ui.grid.grouping', 'ui.grid.expandable']);
Angular Controller code:
medApp.controller("sampleController", ['$scope', '$http', function ($scope, $http) {
$scope.countries = [];
$scope.SelectedCountries = null;
$scope.AfterSelectedCoutries = function (selected) {
if (selected) {
$scope.SelectedCountries = selected.originalObject;
}
}
$http.get("/Home/GetCountry").then(function (d) {
$scope.countries = d.data;
}, function (error) {
alert('Failed');
})
}])
MVC Controller code:
public JsonResult Getcountry()
{
List<Item> listcountry = new List<Item>()
{
new Item()
{
Id=1,
Name= "Crocin"
},
new Item()
{
Id=2,
Name= "Bruffen"
}
};
return Json(listcountry, JsonRequestBehavior.AllowGet);
}
My question is GetCountry method should have a parameter to get the required records but in none of the samples it does.
Any suggestions??
Thanks

Cannot use angular to call web api in cshtml

I have to add an AngularJs control to my cshtml file in a project but as I couldn't make it work I tried to create a simple test application, and now it seems that even this simple app (including only an app module and a controller) is not working!
app.js
(function() {
angular.module('testApp', []);
});
GetProductsCtrl.js
angular.module('testApp.controllers', []); //this is supposed to go in a separate file
angular.module('testApp.controllers')
.controller("GetProductsCtrl", function ($scope, $http) {
$scope.greetings = "hi";
$http({
method: 'GET',
url: "http://localhost:54327/api/products"
})
.success(function (data) {
$scope.products = data;
});
});
ProductsController.cs
public class ProductsController : ApiController
{//inside the web api project and running on http://localhost:54327/
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();
return Ok(product);
}
}
usage
<script src="~/Scripts/angular/common/GetProductsCtrl.js"></script>
<div class="row" ng-app="testApp">
<div>
Here I want to add the control.
{{1+1}} #*even this is not evaluated by angular!(it was working)*#
<ul ng-controller="GetProductsCtrl">
<li ng-repeat="product in products">
{{product.Name}} : $ {{product.Price}}
</li>
</ul>
</div>
</div>
and finally bundle:
bundles.Add(new ScriptBundle("~/bundles/angular").Include(
"~/Scripts/angular.min.js",
"~/Scripts/angular/app.js"
));
What I can guess is that Bundle will try rename your $http provider.
So try .controller("GetProductsCtrl", ["$scope", "$http", function ($scope, $http){
}] instead.

Nothing happens when Angular Href is clicked

I am using Angular Routing with a webapi 2 controller.
Although the default path loads with the correct data, when I click on an item in a list containing a link to a details page, no data is loaded.
The browser shows what I believe to be the correct url (http://localhost:xxxxx/#/details/2) but the DetailsController script file is not called and no method on the webapi2 controller is called.
Here is my main page :
<div class="jumbotron">
<h1>Movies Example</h1>
</div>
#section scripts {
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Client/Scripts/atTheMovies.js"></script>
<script src="~/Client/Scripts/ListController.js"></script>
<script src="~/Client/Scripts/DetailsController.js"></script>
}
<div ng-app="atTheMovies">
<ng-view></ng-view>
</div>
Here is the list partial :
<div ng-controller="ListController as ctrl">
<h1>{{ctrl.message}}</h1>
<h2>There are {{ctrl.movies.length}} Movies in the Database</h2>
<table>
<tr ng-repeat="movie in ctrl.movies">
<td>{{movie.Title}}</td>
<td>
<a ng-href="/#/details/{{movie.Id}}" >Details</a>
</td>
</tr>
</table>
</div>
Here is the details partial:
<div ng-controller="DetailsController as ctrl2">
<h2>ctrl2.message</h2>
<h2>{{movie.Title}}</h2>
<div>
Released in {{movie.ReleaseYear}}
</div>
<div>
{{movie.Runtime}} minutes long.
</div>
</div>
Here is the javascript file to create the angular app:
(function () {
var app = angular.module("atTheMovies", ["ngRoute"]);
var config = function ($routeProvider) {
$routeProvider
.when("/list", { templateUrl: "/client/views/list.html" })
.when("/details/:id", { templatUrl: "/client/views/details.html" })
.otherwise(
{ redirectTo: "/list" });
};
app.config(config);
}());
Here is the javascript file to create the list controller:
(function (app) {
app.controller("ListController", ['$http', function ($http) {
var ctrl = this;
ctrl.message = "Hello World!";
ctrl.movies = [];
$http.get("/api/movie")
.success(function (data) {
ctrl.movies = data;
})
.error(function(status){
ctrl.message = status;
});
}])
}(angular.module("atTheMovies")));
Here is the javascript file to create the details controller:
(function (app) {
app.controller("DetailsController", ['$routeParams', '$http', function ($routeParams, $http) {
var ctrl2 = this;
ctrl2.message = "";
ctrl2.movie = {};
var id = $routeParams.id;
$http.get("/api/movie/" + id)
.success(function(data){
ctrl2.movie = data;
}).error(function (status) {
ctrl2.message = status;
});
}])
}(angular.module("atTheMovies")));
Finally here is the webapi2 controller
public class MovieController : ApiController
{
private MovieDb db = new MovieDb();
// GET: api/Movie
public IQueryable<Movie> GetMovie()
{
return db.Movies;
}
// GET: api/Movie/5
[ResponseType(typeof(Movie))]
public IHttpActionResult GetMovie(int id)
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return NotFound();
}
return Ok(movie);
}
You have a typo in your route config i.e. templatUrl
.when("/details/:id", { templatUrl: "/client/views/details.html" })
should be
.when("/details/:id", { templateUrl: "/client/views/details.html" })

Resources