I have tried to implement some methods from a tutorial javasampleapproach.com/spring-framework/spring-boot/spring-jpa-postgresql-angularjs-example-spring-boot but it doesn't work for me.
When I hit the GET ALL CUSTOMERS-button nothing comes up. When I tried to add a testmessage with the json-text that I have requested from the RestController and just use #scope.allPersons.data the complete json-text come up but if I try to get the valuesin the json-responese it is either undefined or nothing comes up.
First of all, the RestController. I have tried with #RequestMapping(value="/findallresponse", produces = "application/json")and the default from the tutorial as showed in the code. The reason for making my own String Json is that if I responded with the Iteratable-object the response get recursive because of #ManyToMany-relation. And when I troubleshoot I left out the Hobbypart because that was the ManyToMany-relationship value.
#RequestMapping("/findallresponse")
public Response findAllResponse(){
ArrayList firstNameStr=new ArrayList<String>();
ArrayList lastNameStr=new ArrayList<String>();
ArrayList hobbyStr=new ArrayList<String>();
ArrayList idStr=new ArrayList<String>();
boolean startLoop=true;
String jsonPersonBeggining="{\"persons\":[";
String jsonPersonEnd="]}";
String jsonPerson="";
for(Person person : personService.findAll()){
if(startLoop==true)
{
startLoop=false;
}
else
{
jsonPerson+=",";
}
jsonPerson+="{";
jsonPerson+="\"firstName\":\""+person.getFirstName()+"\",";
jsonPerson+="\"lastName\":\""+person.getLastName()+"\",";
//jsonPerson+="\"hobby\":\""+person.getHobby()+"\",";
jsonPerson+="\"id\":\""+person.getId()+"\"";
jsonPerson+="}";
}
jsonPerson=jsonPersonBeggining+jsonPerson+jsonPersonEnd;
return new Response("Done",jsonPerson);
}
Here is the Response-class just as in the tutorial
public class Response {
private String status;
private Object data;
public Response() {
}
public Response(String status, String data) {
this.status = status;
this.data = data;
}
public String getStatus() {
return status;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public void setStatus(String status) {
this.status = status;
}
}
The javascript-file as in the tutorial. The #getResultMessage is to test that the json-string is recieved at all. And it is. But after that I can't access the post in it, for instance
firstName or
lastName
var app = angular.module('app', []);
app.controller('getallpersonsController', function($scope, $http, $location)
{
$scope.showAllPersons = false;
$scope.getAllPersons = function() {
var url = $location.absUrl() + "findallresponse";
var config = {
headers : {
'Content-Type' : 'application/json;charset=utf-8;'
}
}
$http.get(url, config).then(function(response) {
if (response.data.status == "Done") {
$scope.allpersons = response.data;
$scope.showAllPersons = true;
$scope.getResultMessage = $scope.allpersons.data;
} else {
$scope.getResultMessage = "get All Customers Data Error!";
}
}, function(response) {
$scope.getResultMessage = "Fail!";
});
}
});
This is the output on this is the #getResultMessage taken from #scope.allpersons.data
{"persons":[{"firstName":"Adam","lastName":"Johnson","id":"87"},{"firstName":"Anna","lastName":"Persson","id":"90"},{"firstName":"Nils","lastName":"Svensson","id":"93"}]}
And the jsp-file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring Boot Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js">
</script>
<script src="/js/angular.js"></script>
<link rel="stylesheet"
href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"
/>
</head>
<body>
<div class="container" ng-app="app">
<h1>AngularJS - Spring JPA - PostgreSQL</h1>
<div class="row">
<div ng-controller="getallpersonsController" class="col-md-3">
<h3>All Customers</h3>
<button ng-click="getAllPersons()">
Get All Customers
</button>
<div ng-show="showAllPersons">
<ul class="list-group">
<li ng-repeat="persons in allpersons.data">
<h4 class="list-group-item">
<strong>Customer {{$index}}</strong><br />
Id: {{persons.id}}<br />
First Name: {{persons.firstName}}<br />
Last Name: {{persons.lastName}}
</h4>
</li>
</ul>
</div>
<p>{{getResultMessage}}</p>
</div>
</div>
</div>
</body>
</html>
UPDATE!!
Here is some calls on the response if that can give any clue?
data=[object Object] status=200
statustext=undefined
headers=function (d){b||(b=od(a));return d?(d=b[L(d)],void 0===d&&(d=null),d):b} config=[object Object]
Can anyone see if I missed something? In the jsp-file the ng-repeatloop is not working, it doesn't seems to be able to get the value from the json? Thanks
Related
I am very new to chrome extensions and react. An overview of what I am doing is pretty straight forward. I have a chrome extension which takes a screenshot of the activeTab and I want to send that screenshot from the extension to my react app.
From what I understand, I need to dispatch an event from the extension and have the react app listen to it. I have an event listener in the index.html of my react app to listen to events that are dispatched by the extension. I have been unsuccessful in my attempts.
Here's what I have so far:
Chrome extension
popup.js
let tabImage = document.getElementById('tabImage');
let capturedImage = null;
tabImage.onclick = () => {
chrome.tabs.captureVisibleTab(null, (image) => {
document.dispatchEvent(new CustomEvent('csEvent', { data: image })) // send image to react app
viewScreenshot(image);
});
}
//Create a new window in the browser with the captured image
viewScreenshot = (capturedImage) => {
const b64 = capturedImage;
const contentType = 'image/jpeg';
const byteCharacters = atob(b64.substr(`data:${contentType};base64,`.length));
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
const slice = byteCharacters.slice(offset, offset + 1024);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
const blobUrl = URL.createObjectURL(blob);
window.open(blobUrl, '_blank');
}
popup.html
<html lang="en">
<head>
</head>
<body>
<button id="tabImage">Get a screenshot!</button>
<script src='popup.js'></script>
</body>
</html>
reactJS app
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Shots</title>
</head>
<body>
<iframe id="qa_films" src="./demo_course_classic_player_html5-flash-AMP/story.html"
style="position:absolute ;top:0; left:0; bottom:0; right:0; width:100%; height:90%; border:none; margin:0 auto; padding:0; z-index: 0; overflow:hidden; "></iframe>
<div id="screenshot"></div>
</body>
<script>
document.body.addEventListener('csEvent', (event) => {
console.log(event);
})
</script>
</html>
I would like to know which part I am doing it wrong or is there a better way of implementing what I'm trying to achieve. Any help is appreciated. Thanks!
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
Want to create autogenerate code in angular inputbox on refresh page
like rand(function) in php. Im using this script for this. But problem
is its vanished on page refresh not working properly.
<script type="text/javascript">
function randString(x){
var s = "OL-";
while(s.length<x&&x>0){
var r = Math.random();
s+= (r<0.1?Math.floor(r*100):String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65)));
}
return s;
}
document.getElementById("referal_code").value = randString(10);
</script>
<input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>
Try this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getNewID() {
try {
var myDate = new Date();
var varID = myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds();
if (varID.Length > 15) {
varID = varID.substr(0, 15);
}
return varID;
} catch (e) {
console.log(e.message);
}
}
function randString(x){
var s = getNewID();
return s;
}
window.onload = function(){
document.getElementById("referal_code").value = randString(10);
}
</script>
</head>
<body>
<input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>
</body>
</html>
For any attribute in angular world you can use interpolation like this:
<input id="{{randString(10)}}"/>
If you want to have a certain value as id and not get lost after refresh you have to save it on some web storage (localstorage, sessionstorage).
e.g. :
function randString(x){
// ... your function's logic
//Save it in localStorage before returning it
localStorage.inputId = s;
return s;
}
document.getElementById("referal_code").value = localStorage.inputId || randString(10)
I have a Web API where my repository class is:
public class myRepository
{
public myClasses.Type[] GetAllTypes()
{
return new myClasses.Type[]
{
new myClasses.Type
{
typeId="1",
typeVal = "New"
},
new myClasses.Type
{
typeId="2",
typeVal = "Old"
}
};
}
public myClasses.Employee[] GetAllEmployees()
{
return new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
}
public bool VerifyEmployeeId(string id)
{
myClasses.Employee[] emp = new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
for (var i = 0; i <= emp.Length - 1; i++)
{
if (emp[i].empId == id)
return true;
}
return false;
}
}
and here is my controller:
public class myClassesController : ApiController
{
private myRepository empRepository;
public myClassesController()
{
this.empRepository = new myRepository();
}
public myClasses.Type[] GetTypes()
{
return empRepository.GetAllTypes();
}
public myClasses.Employee[] GetEmployees()
{
return empRepository.GetAllEmployees();
}
[HttpGet]
public bool VerifyEmployee(string id)
{
return empRepository.VerifyEmployeeId(string id);
}
}
Now I have created a web application where I included angularJS. Here is my html (EmployeeLogin.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Employee ID</title>
<script src="../../Scripts/jquery-2.2.0.min.js"></script>
<script src="../../Scripts/angular-ui/ui-bootstrap.min.js"></script>
<script src="../../Scripts/angular.js"></script>
<script src="EmployeeLoginCtrl.js"></script>
</head>
<body ng-app="myClassesApp">
<div ng-controller="myClassesController">
<form ng-submit="ValidateEmployeeId()" method="get" id="frmLogin" action="">
<input ng-model="empId" type="text" id="txtEmpId" />
<br />
<input type="submit" value="Submit" id="btnSubmit" />
<br />
<span id="lblMsg">{{EmployeeValidate}}</span>
</form>
</div>
</body>
</html>
What I want to accomplish is when the user enters their ID, I want to call myController function VerifyEmployee, pass it the ID entered by the user and output message of success or failure to the web page.
I am in need of some assistance fixing up my angular controller. here is what I got so far:
(function () {
angular.module("myClassesApp", []).controller("myClassesController", myValidateFunction);
myValidateFunction.$inject("$scope", "$http");
function myValidateFunction($scope, $http) {
$scope.ValidateEmployeeId = function () {
alert($scope.empId);
$http.get('http://localhost:49358/api/myClasses/VerifyEmployee/' + $scope.empId).
then(function (result) {
alert(result);
$scope.EmployeeValidate = result.data;
});
}
};
})();
My main question is how do I pass the id from the textbox to the angular controller?
Also how I ensure my angular function is only called when the form is submitted by the user, not when the page loads initially?
Can someone please point me in the right direction in regards to getting data from Web API and displaying it on the page?
So far the page loads, immediately displays "false" in the message label. then I enter ID and click submit and then nothing happens. ow can I ensure that angular function gets called?
So, in your UI, whatever you're data-binding to (ng-model, etc..) you have access to in Angular. In your example, you have <input ng-model="empId" type="text" id="txtEmpId" /> but I don't see a $scope.empId..Where is empId coming from then?
UI
<div ng-app ng-controller="myClassesController">
<div>Enter your User ID:</div>
<input ng-model="empId"></input>
<input type="submit" ng-click="checkUser()" value="Login"></input>
</div>
Controller
function myClassesController($scope) {
$scope.empId = '';
$scope.checkUser = function () {
// hit your api with user id
alert($scope.empId);
}
}
Here's a working example for you : JSFiddle
I am looking for a VERY simple example that shows wiring up Knockback code to a backbone model that connects via RESTful service. I am using ServiceStack|c# backend. All of the links below are too complicated and use localStore rather than a RESTful service via url. I also prefer to see examples in Javascript not CoffeeScript.
My example url is something like localhost/entities where hitting this will cause the RESTful webservice to return all of the entities. Hitting it with localhost/entity/1 would return the entity with an Id of 1.
_http://kmalakoff.github.com/knockback/index.html
_https://github.com/kmalakoff/knockback-reference-app/
_https://github.com/addyosmani/todomvc
The following is the example from knockback tutorial on the first link:
Models, Collection, ViewModel, and Bindings:
// Generated by CoffeeScript 1.3.3
var model, view_model;
model = new Backbone.Model({
first_name: "Planet",
last_name: "Earth"
});
view_model = kb.viewModel(model);
view_model.full_name = ko.computed((function() {
return "" + (this.first_name()) + " " + (this.last_name());
}), view_model);
ko.applyBindings(view_model, $('#kb_view_model_computed')[0]);
But there is no mention of how you would wire the backbone model up to your RESTful webservice.
There are examples of how do this via Backbone but I am uncertain as to how things change when using Knockback.
The following links were found, but not helpful:
_http://stackoverflow.com/questions/7992431/using-knockoutjs-backbone-together
_http://stackoverflow.com/questions/9704220/is-knockback-js-production-ready
_http://stackoverflow.com/questions/10434203/defining-models-on-server-side-when-using-mvvm-with-knockout-js
Thanks in advance for any assistance provided. Btw you don't want hyperlinks you get underscores... ;)
With much help and support from Kevin Malakoff from the great Knockback project I was able to get a small example working! I used the ServiceStack Backbone Todos project as a starting point.
c# file: Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using ServiceStack.Redis;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
namespace MyApp
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonService : RestServiceBase<Person>
{
public static Person kevin = new Person { Id = 1, FirstName = "Kevin", LastName = "Malakoff" };
public static Person scott = new Person { Id = 2, FirstName = "Scott", LastName = "Idler" };
public static List<Person> people = new List<Person> { kevin, scott };
public override object OnGet(Person person)
{
if (person.Id != default(int))
return people[person.Id-1];
return people;
}
public override object OnPost(Person person)
{
return base.OnPost(person);
}
public override object OnPut(Person person)
{
return OnPost(person);
}
public override object OnDelete(Person person)
{
return base.OnDelete(person);
}
}
public class AppHost : AppHostBase
{
public AppHost() : base("MyApp", typeof(PersonService).Assembly) { }
public override void Configure(Funq.Container container)
{
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
Routes
.Add<Person>("/persons")
.Add<Person>("/persons/{Id}");
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
new AppHost().Init();
}
}
}
html file: default.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MyApp2</title>
<script>window.JSON || document.write('<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">\x3C/script>')</script>
<script src="Scripts/jquery-1.8.0.js" type="text/javascript" ></script>
<script src="Scripts/knockback-full-stack-0.16.1.js" type="text/javascript" ></script>
<script src="myapp.js" type="text/javascript" ></script>
</head>
<body>
<div id="myapp">
<div class="title">
<h1>MyApp</h1>
</div>
<div class="content">
<div id='kb_observable'>
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
<p>Hello, <span data-bind="text: fullName"></span>!</p>
</div>
<div id="kb_collection_observable">
<div data-bind="if: persons">
<span>Has Persons</span>
</div>
<div data-bind="foreach: persons">
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
</div>
</div>
</div>
</div>
</body>
</html>
javascript file: myapp.js
$(function() {
//model
var PersonModel = Backbone.Model.extend({ urlRoot: '/MyApp/persons' });
var model = new PersonModel({ id: 1 });
model.fetch();
//viewmodel
var PersonViewModel = function (person) {
this.firstName = kb.observable(person, 'firstName');
this.lastName = kb.observable(person, 'lastName');
this.fullName = ko.computed((function () {
return "" + (this.firstName()) + " " + (this.lastName());
}), this);
};
var personViewModel = new PersonViewModel(model);
//binding
ko.applyBindings(personViewModel, $('#kb_observable')[0]);
//model
var PersonsModel = Backbone.Collection.extend({ model: PersonModel, url: '/MyApp/persons' });
var personsModel = new PersonsModel();
personsModel.fetch();
//viewmodel
var PersonsViewModel = function (persons) {
this.persons = kb.collectionObservable(persons)
};
var personsViewModel = new PersonsViewModel(personsModel);
//binding
ko.applyBindings(personsViewModel, $('#kb_collection_observable')[0]); });
I put together a very simple example. It assumes you already know how to use backbone and knockout so this just gives a quick example of how they can be used together
http://coder2.blogspot.com/2013/02/backbonejs-and-knockoutjs.html