Not able to display the value from Json response - angularjs

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

Related

Error trying to diff '[object Object]'. Only arrays and iterables are allowed but i dont see anything wrong with my code

I have been having this problem for the past week, I have searched everywhere but wasn't able to find a problem.
My service
private texst!: Posts[];
public getPosts(): Observable<Posts[]>
{
return this.http.get<Posts[]>("http://localhost/projects/php_rest_api/api/post/read.php").pipe(map((data) => {
return this.texst = data;
}));
}
My Component, here i add the service and run the function to get the data from my database
public test: Posts[] = [];]
constructor(public postService: PostsService,
private http: HttpClient) {}
ngOnInit(): void {
this.getPosts();
}
public getPosts()
{
this.postService.getPosts().subscribe((response) => {
this.test = response;
console.log(this.test);
})
}
My html
<div>
<button (click)="getPosts()"></button>
<div *ngFor="let test of test">
{{test.title}}
</div>
</div>
Change this, rename your var test to testItem because it's already used:
<div>
<button (click)="getPosts()"></button>
<div *ngFor="let testItem of test">
{{testItem.title}}
</div>
</div>
Managed to fix it
changed the response to object.values in my getPosts() function
public getPosts()
{
this.postService.getPosts().subscribe((response) => {
this.test = Object.values(response);
console.log(this.test);
})
}
It means you're trying to iterate over object, but you think it's an array.
If that image is a log of the response, you better do:
public getPosts()
{
this.postService.getPosts().subscribe((response) => {
this.test = response.data; // <.. this changes!
})
}
and in template:
<div *ngFor="let testItem of test">
{{testItem.title}}
</div>

"Error in .People/Component class PeopleComponent - inline template:93:8 caused by: Error trying to diff '[object Object]'"

i am able to fetch data from the database which is showing in my network tab alright but my app gives an error when i am trying to display the fetched data in my table. The error display ""Error in .People/Component class PeopleComponent - inline template:93:8 caused by: Error trying to diff '[object Object]'""
//component
export class PeopleComponent {
People: Peoples[] = [];
constructor(private httpService: HttpService, private router: Router) {
this.httpService.getPeople()
.subscribe(data => {
this.People = data;
}
);
}
//service
getPeople() {
let headers = new Headers({ 'Authorization': 'Bearer ' + this.auth.token });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://example.com', options)
.map((response:Response) => response.json());
}
//table
<table class="table" id="table" >
<tr>
<th>#</th>
<th>Group</th>
<th>Country</th>
</tr>
<tbody>
<tr *ngFor="let people of People" >
<td>{{people.group}}</td>
<td>{{people.country}}</td>
</tr>
</tbody>
</table>
// updated table
<tbody>
<tr *ngFor="let key of People | keys; let i = index" >
<td>{{i + 1}}</td>
<td>{{People[key].first_name + " " + People[key].last_name}}</td>
<td>{{People[key].group}}</td>
<td>{{People[[key].country}}</td>
</tr>
</tbody>
//pipe.ts
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value) : any {
if(value) {
return Object.keys(value)
}
}
}
//image
*ngFor only supports iterating an array, not arbitrary classes.
You can use a pipe for example like the following to get an array of keys you can iterate:
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value) : any {
if(value) {
return Object.keys(value)
}
}
}
<tr *ngFor="let key of People | keys " >
<td>{{People[key].group}}</td>
<td>{{People[key].country}}</td>
</tr>
</tbody>

Cannot find name 'headers'. in angular 2

enter image description here
I am working on angular 2.this is my ts file I called getRandomQuote() method in constructor.
But when i run the project i get below error:-
Cannot find name 'headers'. Did you mean the instance member 'this.headers'?
import {Component, ViewEncapsulation, Injectable} from '#angular/core';
import {PaginatePipe, PaginationControlsCmp, PaginationService} from 'ng2-pagination';
import { Http, Response, Headers,RequestOptions } from 'angular2/http';
import {BasicTablesService} from './basicTables.service';
import {BaCard} from '../../../../theme/components';
import {HoverTable} from './components/hoverTable';
import {BorderedTable} from './components/borderedTable';
import {CondensedTable} from './components/condensedTable';
import {StripedTable} from './components/stripedTable';
import {ContextualTable} from './components/contextualTable';
import {ResponsiveTable} from './components/responsiveTable';
import {AuthHttp, AuthConfig, AUTH_PROVIDERS } from 'angular2-jwt';
import {HTTP_BINDINGS} from 'angular2/http';
#Component({
selector: 'basic-tables',
viewProviders: [PaginationService],
pipes: [PaginatePipe, ResponsiveTable, ContextualTable],
encapsulation: ViewEncapsulation.None,
directives: [BaCard, HoverTable, BorderedTable, CondensedTable, StripedTable, ContextualTable, ResponsiveTable, PaginationControlsCmp,HTTP_BINDINGS],
styles: [require('./basicTables.scss')],
template: `
<todo-search></todo-search>
<table class="table table-hover">
<div >Enter ID: <input type="text" #listFilter (keyup)="0" style="color:black" /></div> <div>Alert on click<button (click)="clicked()" style="color:black">Click</button></div>
<span>{{ test }}</span>
<tr class="black-muted-bg">
<th class="align-left">ID</th>
<th class="align-left">Name</th>
<th class="align-left">Protocol</th>
<th class="align-left">Inbound Business Process</th>
<th class="align-left">Outbound Business Process</th>
</tr>
<tbody>
<tr *ngFor="let item of randomQuote | paginate: { itemsPerPage: 20, currentPage: p } | ResponsiveTable:listFilter.value ">
<td>{{item.connectionId}}</td>
<td>{{item.name}}</td>
<td>{{item.protocol}}</td>
<td>{{item.inBoundBPName}}</td>
<td>{{item.outBoundBPName}}</td>
</tr>
</tbody>
<pagination-controls (pageChange)="p = $event" #api></pagination-controls>
</table>
`,
providers: [BasicTablesService]
})
export class BasicTables {
public body = JSON.stringify(
{
"startIndex": 0,
"numofIds": 15,
"programId": null,
"emailId":"admin#justransform.com",
"searchStr":"",
"transactionId":"",
"status":"",
"srcConnectionName":"",
"destConnectionName":"",
"inBoundBPName":"",
"outBoundBPName":"",
"fileContent":""
}
);
public headers = new Headers({ 'Content-Type': 'application/json' });
public options = new RequestOptions({ headers: headers });
private url = 'http://uat.justransform.com:8080/justransform/transaction/find?sortByColumn=transactionId&sortByOrder=Desc';
randomQuote:Array<any> = [];
getRandomQuote() {
this.http.post(this.url, this.body, this.options)
.map((res:Response) => res.json())
.subscribe(
data => {this.randomQuote = data},
err => this.logError(err),
() => console.log('Random Quote Complete')
);
}
logError(err) {
console.error('There was an error: ' + err);
}
clicked(event) {
alert("Alert");
}
constructor(public http: Http) {
this.getRandomQuote();
}
}
Your code defines the headers attribute in the class context and tries to access it directly after that using headers.
public headers = new Headers({ 'Content-Type': 'application/json' });
public options = new RequestOptions({ headers: headers });
The error message you get for that specifically tells you what to try:
Cannot find name 'headers'. Did you mean the instance member 'this.headers'?
This is because you defined headers in the class context. To properly access it, you have to use this.headers:
public options = new RequestOptions({ headers: this.headers });
// ^ here
See TypeScript Classes for more information.

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
}
}

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

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());
}

Resources