Getting 404 while sending data from controller.js to spring controller - angularjs

I have to send id to spring controller but I am getting 404. I am using angularjs, spring and mongodb.I am getting data perfectly. Onclick of approve/reject button id is being passed to controller.js but after that I am getting 404.
Also I have to pass index of row to controller so that i can remove row once data is updated in database. How to do this? Please provide some logic.
Html
<tbody>
<tr ng-repeat="task in taskDetails">
<td style="text-align: center;">{{task.name}}</td>
<!-- <td style="text-align: center;">{{task.owners}}</td> -->
<td style="text-align: center;">
<span ng-repeat="owner in task.owners">{{owner.ownerName.name}}{{$last ? '' : ', '}}</span>
</td>
<td style="text-align:center;">
<button class="btn btn-mini btn-primary" ng-click="approveTask(task)" value="approveTask">Approve</button>
<button class="btn btn-mini btn-danger" ng-click="rejectTask(task)" value="rejectTask">Reject</button>
</td>
</tr>
</tbody>
Controller
//controller.js
$scope.approveTask = function(task) {
alert(task);
var dataObj = {
id : task.id
};
$http.post('/userNotification/task/approve', dataObj).success(function (data) {
alert("Approved! "+ data);
});
}
$scope.rejectTask = function(task) {
alert(task);
var dataObj = {
id : task.id
};
$http.post('/userNotification/task/reject'+ dataObj).success(function(data) {
alert("Rejected! "+ data);
});
}
Spring Controller
//spring controller
package com.rmtool.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rmtool.mongo.dao.TaskDAO;
import com.rmtool.service.MongoService;
#Controller
#RequestMapping("/userNotification")
public class UserNotificationController {
#Autowired
MongoService mongoService;
#RequestMapping(value = "/fetchTaskForApproval",
method = RequestMethod.GET)
public #ResponseBody List<TaskDAO> notification(){
System.out.println("entering notification");
List<TaskDAO> taskDAOLists=new ArrayList<TaskDAO>();
taskDAOLists = mongoService.fetchPendingTask("Pending Approval");
System.out.println("exiting notification");
System.out.println(taskDAOLists);
return taskDAOLists;
}
#RequestMapping(value = "/task/approve", method = RequestMethod.POST)
public #ResponseBody void approveTask(#RequestBody TaskDAO task){
System.out.println("task Id :"+task.getId());
mongoService.approvePendingTask(task.getId());
}
#RequestMapping(value = "/task/reject/{id}", method = RequestMethod.POST)
public #ResponseBody void rejectTask(#PathVariable("id") String id){
mongoService.rejectPendingTask(id);
}
}

This is working fine...
//controller.js
$scope.approveTask = function($index,$task) {
$scope.currentIndex = $index;
//alert($task+$scope.currentIndex);
var dataObj = {
id : $task.id
};
$http.post('userNotification/approve',dataObj).success(function (data) {
alert("Approved! ");
$scope.taskDetails.splice($scope.currentIndex, 1);
$scope.currentIndex = -1;
});
}
$scope.rejectTask = function($index,$task) {
$scope.currentIndex = $index;
//alert($task+$scope.currentIndex);
var dataObj = {
id : $task.id
};
$http.post('userNotification/reject', dataObj).success(function(data) {
alert("Rejected! ");
$scope.taskDetails.splice($scope.currentIndex, 1);
$scope.currentIndex = -1;
});
}
//SpringController
#RequestMapping(value = "/approve", method = RequestMethod.POST)
public #ResponseBody void approveTask(#RequestBody TaskDAO task){
System.out.println("task Id :"+task.getId());
mongoService.approvePendingTask(task.getId());
}
#RequestMapping(value = "/reject", method = RequestMethod.POST)
public #ResponseBody void rejectTask(#RequestBody TaskDAO task){
System.out.println("task Id :"+task.getId());
mongoService.rejectPendingTask(task.getId());
}

Related

How to Send multiple values from Asp.Net WebApi to Angularjs Controller?

WebApi Controller.. How to send this value to Angularjs controller (bill = q.TotalBill;)? I have send this (return Ok(gridlist);) into JSON form into angularjs controller
public static double bill; // this is static variable on top of a class
[System.Web.Http.Route("api/Products/gridpro/{id}")]
public IHttpActionResult GetGrid(int id)
{
var q = db.products.Find(id);
if (q != null)
{
var check = gridlist.Where(x => x.Id == id).FirstOrDefault();
if (check != null)
{
check.ProductQty += 1;
check.TotalAmount = check.ProductQty * check.ProductRate;
}
else
{
q.ProductQty = 1;
q.TotalAmount = q.ProductQty * q.ProductRate;
gridlist.Add(q);
}
q.TotalBill = gridlist.Sum(x => x.TotalAmount);
foreach (var item in gridlist)
{
item.TotalBill = q.TotalBill;
}
bill = q.TotalBill; //How to send this value to Angularjs controller
return Ok(gridlist);
}
else
{
return NotFound();
}
}
Anagularjs Code: I see all the data into the HTML using this ($scope.gridproducts) but I want to show (bill = q.TotalBill;) this single value into HTML code
$scope.OnProChange = function (Pro) {
var id = Pro.Id;
$http.get("/api/Products/gridpro/" + id).then(function (response) {
console.log(JSON.stringify(response.data))
$scope.gridproducts = response.data;
})
}
HTML code:How I can show total bill value I use {{gridproducts.TotalBill}} this but nothing works.
<tbody>
<tr ng-repeat="item in gridproducts">
<td>
<a class="delete"><i class="fa fa-times-circle-o"></i></a>
</td>
<td class="name">{{item.ProductName}}</td>
<td>{{item.ProductRate}}</td>
<td>
<input class="form-control qty" style="width:50px" onchange="UpdatePurchaseItem('36',this.value)" value="{{item.ProductQty}}">
</td>
<td>{{item.TotalAmount}}</td>
</tr>
<tr></tr>
<tfoot>
<tr>
<th colspan="2"></th>
<th colspan="2"><b>Total</b></th>
<th><b>{{gridproducts.TotalBill}}</b></th>
</tr>
<tr>
<th colspan="2"><b></b></th>
<th colspan="2"><b>Total Items</b></th>
<th><b>25</b></th>
</tr>
</tfoot>
</tbody>
if you want send multiple values to angularjs , you may create complex type for that.
for example,
in c# code
Public Class GridDataModel<T>
{
public T ItemList{get;set;}
public int TotalBill{get;set}
}
then when you return data to js
var gridData=new GridDataModel<products>()
{
ItemList=gridlist,
TotalBill=q.TotalBill
}
return Ok(gridData);
after doing this , you can create another propert for js scope
$http.get("/api/Products/gridpro/" + id).then(function (response) {
console.log(JSON.stringify(response.data))
$scope.gridproducts = response.data.ItemList;
$scope.totalBill = response.data.TotalBill;
})

ionic 2 get ion-input text to refresh

I have a page with an ion-input in a FormGroup.
When they go to the page, data is loaded from a server. When the data comes in I want the ion-input to be filled in with the data from the server, which the user can then edit and save.
I cannot get the ion-input to show the data. (it remains blank)
Here is the page:
import { Component,ViewChild } from '#angular/core';
import { Validators, FormBuilder, FormGroup } from "#angular/forms";
import { NavController, App, MenuController, NavParams, AlertController,Content } from 'ionic-angular';
import {DomSanitizer,SafeResourceUrl} from '#angular/platform-browser';
import { TabsPage } from '../tabs/tabs';
// Providers
import { ProjectDetailService } from '../../providers/project-detail-service';
#Component({
selector: 'page-form',
templateUrl: 'form.html',
})
export class FormPage {
#ViewChild(Content) content: Content;
newObject: FormGroup;
object: any = {};
objectKey: string = "";
pageTitle: string = "Create New";
videoURL: SafeResourceUrl;
sanitizer: DomSanitizer;
updating: boolean = false;
constructor( public formBuilder: FormBuilder,
public service: ProjectDetailService,
public navParams: NavParams,
public app: App,
public alertCtrl: AlertController,
sanitizer: DomSanitizer ) {
this.sanitizer = sanitizer;
this.newObject = this.formBuilder.group({
name: this.object.name
});
}
setData()
{
this.newObject.value.name = this.object.name;
//none of these work:
//this.content.resize();
//window.location.reload();
//this.app.getRootNav().setRoot(this.app.getRootNav().getActive().component);
}
ionViewDidLoad()
{
this.objectKey = this.navParams.get('projectKey');
console.log("objectkey="+this.objectKey)
this.service.getProject(this.objectKey).subscribe( ( data: any ) => {
this.object = data;
this.setData();
})
}
This is the html:
<ion-content padding>
<form [formGroup]="newObject" (ngSubmit)="save()">
<ion-item>
<ion-label>Project Name</ion-label>
<ion-input type="text" formControlName="name"></ion-input>
</ion-item>
</form>
</ion-content>
I think FormBuilder is not a two way bindier Instead use a simple two way binding like this
<ion-input type="text" [(ngModel)]="name" formControlName="name"></ion-input>
and access as
this.name = 'something';

Not able to display the value from Json response

I am trying to get a json web response from jersey web service using hibernate.The values are returned from database as i checked in the console.The problem is that when i try to print that in the angular like this
<h1>Welcome to Hibernate Jersey Angular CMS</h1>
<div id='err'></div>
<a href="add.html" class='btn btn-success'>New Article</a>
<p>
<div>
<table id='blogList' class="table table-bordered" ng-controller='MyController'>
<tr>
<th>Latest Articles</th>
<th>Actions</th>
</tr>
<tr ng-repeat='elem in data'>
<td>{{elem.id}}</td>
<td><a class='btn btn-warning' href="modify.html?id={{elem.id}}">Modify</a></td>
</tr>
</table>
</div>
</body>
<script src='javascripts/jquery2.1.3/jquery.min.js'></script>
<script src='javascripts/bootstrap3.3.2/js/bootstrap.min.js'></script>
<script src='javascripts/angular1.2.19/angular.js'></script>
<script src='javascripts/json/json2.js'></script>
<script>
function MyController($scope, $http) {
//$scope.data = [{title: 'welcome hello'},{title: 'great testing'}];
$http.get("webapi/blog/list", {}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
alert("error");
})
}
</script>
</html>
the value is not displayed.It is displayed blank like this
I know i am getting proper response as the number of rows min the image is same as the number of entries in the table.This is my code for hibernate
public List<Love> getAllLeaves() {
Session session = HibernateTest.getSession();
String hql = "from Love";
Query qry = session.createQuery(hql);
List<Love> list = qry.list();
Iterator i=list.iterator();
while(i.hasNext())
{
Love l=(Love) i.next();
//System.out.println("staretd");
}
session.close();
return list;
}
and the jersey code
#GET
#Path("list")
#Produces({ "application/json" })
public List<Love> list() {
List l= new LeaveDao().getAllLeaves();
Iterator i=l.iterator();
while(i.hasNext())
{
Love m=(Love)i.next();
System.out.println(m.getLove());
}
return l;
}
and bean class
package com.king.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.ws.rs.QueryParam;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
public class Love {
public Love(String Love) {
this.id = Love;
}
public Love()
{}
public String getLove() {
return id;
}
public void setLove(String Love) {
this.id = Love;
}
#Id
#QueryParam("id")
private String id;
}
added network response

Pushing multiple entries and saving them in database through AngularJS

I am stuck saving multiple rows I pushed in "$scope.arr" to my SQL Server database. I have my code below and it works fine but when I click on "Save To DB" button after adding/pushing some entries by pressing "Add Person" button, it passes a row with null values to SQL Server database. Please guide me where I am doing the mistake:
I also heard about using angular.forEach loop but I am confused using that too.
I have my model class "TestModel.cs" here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProj.Models
{
public class TestModel
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
My MVC Controller named TestController's Add method here:
[HttpPost]
public string AddPerson(TestModel test)
using (TestContext db = new TestContext())
{
if (test != null)
{
db.TestModels.Add(test);
db.SaveChanges();
return "Successful";
}
else
{
return "Failed";
}
}
}
My AngularJS script here:
var app = angular.module("TestApp", []);
app.controller("TestCtrl", function ($scope, TestService) {
$scope.arr = [];
$scope.addPerson = function () {
var myobj = {
FirstName: $scope.firstname,
LastName: $scope.lastname
}
$scope.arr.push(myobj);
};
$scope.savePerson = function () {
var TestData = TestService.AddPer($scope.arr);
TestData.then(function (msg) {
alert(msg.data);
}, function () {
alert('Error In Adding Person');
});
};
});
app.service("TestService", function ($http) {
this.AddPer = function (person) {
var response = $http({
method: "post",
url: "/Test/AddPerson",
data: JSON.stringify(person),
dataType: "json",
});
console.log(response);
return response;
}
});
And my Index.cshtml file here:
<div ng-controller="TestCtrl">
<form>
FirstName: <input class="form-control" ng-model="firstname" /><br />
LastName: <input class="form-control" ng-model="lastname" /><br />
<button class="btn btn-success" ng-click="addPerson()">Add Person</button>
<button class="btn btn-success" ng-click="savePerson()">Save To DB</button>
<table class="table table-bordered">
<tr>
<th>S. No</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="a in arr">
<td>{{$index+1}}</td>
<td>{{a.FirstName}}</td>
<td>{{a.LastName}}</td>
</tr>
</table>
</form>
</div>
<script src="~/Scripts/MyAngular/Module.js"></script>
Your help will be appreciated. Thanks!
Then server side action should expect collection of TestModel, you could us List there. If you [FromBody] before parameter, you don't need to stringify data before posting it to server.
Code
[HttpPost]
public string AddPerson([FromBody] List<TestModel> test)
using(TestContext db = new TestContext()) {
test.forEach(t=> {
if (t != null) {
db.TestModels.Add(t);
return "Successful";
} else {
return "Failed";
}
});
db.SaveChanges(); //save context at the end, when no error occurs
}
}
The problem was in my Server Side Code i.e, my C# controller, this method worked:
[HttpPost]
public void AddPerson(List<TestModel> test)
{
using (TestContext db = new TestContext())
{
foreach(var t in test)
{
if (t != null)
{
db.TestModels.Add(t);
Console.WriteLine("Success");
}
}
db.SaveChanges(); //save context at the end, when no error occurs
}
}

How Exporting a table to Excel?

what is the best way of this? I have table and it's data coming from api. I used angularJs for data. Here my source codes:
Here's my table in Index:
<div style="width:1100px; max-height:480px; overflow:scroll; border-top:1px solid #808080">
<table class="table">
<tr>
<th>AdaNo</th>
<th>ParselNo</th>
<th>CiltNo</th>
<th>SayfaNo</th>
<th>ZeminTip</th>
<th>İl</th>
<th>İlçe</th>
<th>Mahalle</th>
<th>Kurum</th>
<th>Alan</th>
<th>Pay</th>
<th>Nitelik</th>
<th>EdinmeSebep</th>
<th>Ad</th>
<th>SoyAd</th>
<th>TcKimlikNo</th>
<th>HissePay</th>
<th>HissePayda</th>
</tr>
<tr data-ng-repeat="zemin in Zeminler">
<td>{{zemin.AdaNo}}</td>
<td>{{zemin.ParselNo}}</td>
<td>{{zemin.CiltNo}}</td>
<td>{{zemin.SayfaNo}}</td>
<td>{{zemin.ZeminTip.Ad}}</td>
<td>{{zemin.Il.Ad}}</td>
<td>{{zemin.Ilce.Ad}}</td>
<td>{{zemin.Mahalle.Ad}}</td>
<td>{{zemin.Kurum.Ad}}</td>
<td>{{zemin.AnaTasinmaz.Alan}}</td>
<td>{{zemin.KatMulkiyeti.ArsaPay}}/{{zemin.KatMulkiyeti.ArsaPayda}}</td>
<td>{{zemin.AnaTasinmaz.Nitelik}}</td>
<td>{{zemin.Hisseler[0].EdinmeSebep}}</td>
<td>{{zemin.Hisseler[0].Kisi.GercekKisi.Ad}}{{zemin.Hisseler[0].Kisi.TuzelKisi.Ad}}</td>
<td>{{zemin.Hisseler[0].Kisi.GercekKisi.SoyAd}}</td>
<td>{{zemin.Hisseler[0].Kisi.GercekKisi.TcKimlikNo}}</td>
<td>{{zemin.Hisseler[0].HissePay}}</td>
<td>{{zemin.Hisseler[0].HissePayda}}</td>
</tr>
</table>
</div>
Here's my Apis for this Data:
[Route("api/TapuZeminApi/GetZemins")]
[HttpPost]
public string GetZeminsFromZeminArg(object arg)
{
ZeminArg zemArg = SConvert.DeserializeJSON<ZeminArg>(arg.ToString());
List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromArgs(zemArg);
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
}
// GET api/<controller>/5
public string GetZeminsFromTcNo(long id)
{
List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromTcNo(id.ToString());
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
}
public string GetZeminsFromKurumId(long id)
{
List<TapuZeminModel> zeminList = TapuModule.GetZeminListKurumId(id);
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
}
Article
I used it in my solution like:
First made ExportToExcelService.Js:
angular.module('TapuAppModule')
.factory('Excel', function tapuExcelFactory($window) {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
base64 = function (s) { return $window.btoa(unescape(encodeURIComponent(s))); },
format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
return {
tableToExcel: function (tableId, worksheetName) {
alert('Olcak olcak')
var table = $(tableId),
ctx = { worksheet: worksheetName, table: table.html() },
href = uri + base64(format(template, ctx));
return href;
}
};
})
and here my controller tapuController.js:
$scope.exportToExcel = function (tableId) {
$scope.exportHref = Excel.tableToExcel(tableId, 'sheet name');
$timeout(function () { location.href = $scope.fileData.exportHref; }, 100); // trigger download
};
and my button like this in Index:
<button class="btn btn-link" ng-click="exportToExcel('#dataTable')">
<span class="w-icon-page-excel"></span> Export to Excel
</button>
When I click button I'm getting alert that in ExportToExcelService.Js 'Olcak Olcak'. So I think it can be triggered method in ExportToExcelService.Js. Then I got this error like at console in Chrome:
TypeError: Cannot read property 'exportHref' of undefined
at tapuController.js:81
at angular.js:17682
at completeOutstandingRequest (angular.js:5387)
at angular.js:5659
Why I'm getting this error? What should I do?
Try to change the location.href value by $scope.exportHref; without fileData.
$timeout(function () { location.href = $scope.exportHref; }, 100); // trigger download
that works for me.

Resources