I want show elastic search data on web page that using angular js.
however, not bring data from elasticsearch with that message
Is there anything I need to add or fix in my code?
if anyone answers to me I really appreciate
I have attached an execution screen.
thank you.
Execution screen:
enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController"></div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'http://localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
"match_all" : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
}).catch(function (err) {
if (err.status === 404) {
alert("error 404" );
} else {
alert("error : " + err );
}
});
});
</script>
</body>
</html>
Related
I am developing one PWA of the ionic capacitor and there is a requirement to load another website in an iframe so from one of the ionic app component I called another site.
iframe.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="end" (click)="goBack()">
Close
<ion-icon slot="icon-only" name="close-outline"></ion-icon>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<iframe #iframe height="100%" width="100%" title="test"></iframe>
</ion-content>
iframe.page.ts
export class IframePage implements OnInit, AfterViewInit {
userId = localStorage.getItem('userId');
gameData: any;
gameUrl: any;
docId;
#ViewChild('iframe') iframe: ElementRef;
constructor(private navCtrl: NavController,
private authSrv: AuthService,
private commanSrv: CommannService,
private router:Router) {
firebase.analytics().logEvent('Web_game');
this.iframe.nativeElement.setAttribute('src', 'anotherdomain.com?UID=sadsajdhsakjhdasjhkjsd');
window.addEventListener('message', (event) => {
console.log(event.data);
if (event.data.res === 'win') {
// let routename = commanSrv.getLastRoute();
// navCtrl.navigateForward(routename || 'home_tab');
this.router.navigate(['arcade-outcome', { type: 'arcade_win' }]);
} else if (event.data.res === 'loss'){
this.router.navigate(['arcade-outcome', { type: 'arcade_lose' }]);
} else {
// if (event.data === 'closed') {
let routename = commanSrv.getLastRoute();
navCtrl.navigateBack(routename || 'home_tab');
// }
}
});
}
}
And now
another site is made up of HTML and javascript and here is code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="assets/icon/favicon.png" />
<link rel="stylesheet" type="text/css" href="./assets/css/custom.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-database.js"></script>
<script src="scripts/firebase.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
<title>HTML 5 game application</title>
</head>
<body>
<p>Loader screen</p>
<div class="loader"></div>
<script>
$(document).ready(function(){
const serverUrl = 'https://us-central1-domain.cloudfunctions.net/';
var token;
var xhttp = new XMLHttpRequest();
var gamePlayData;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const userId = urlParams.get('UID')
const gamePlay = urlParams.get('gameplay')
const mode = urlParams.get('mode')
function getUserDetails(token) {
console.log("getUserDetails start token ", token);
console.log(firebase);
firebase.auth().signInWithCustomToken(token).then((userCredential) => { // execution stop from here.
console.log("getUserDetails end");
var user = userCredential.user;
if (user !== null) {
window.location.replace(`anotherdomain.com/start.html?id=${userId}&gamePlay=${gamePlay}`);
}
})
.catch((error) => {
console.log('error in catch: ', error);
var errorCode = error.code;
var errorMessage = error.message;
// window.history.back();
alert('User is not logged in.')
// parent.postMessage('closed', '*');
});
}
function checkAuth() {
console.log("ajax call start");
$.ajax({
type: "POST",
url: serverUrl + 'checkAuthStatus',
data: { uid: userId },
success: function (response) {
console.log("ajax call end");
//if request if made successfully then the response represent the data
getUserDetails(response.result);
},
error: function (err) {
console.log(err);
}
});
}
checkAuth();
});
</script>
From the line
firebase.auth().signInWithCustomToken(token).then(() => {
Execution cancelled and iframe got closed , window.addEventListener('message', (event) => { got called navigated to ionic application back.
The surprising is, this issue only occurs in iPhone whereas for android it is working fine.
When navigating to another domain site 3rd time then it working and got the success in firebase.auth().signInWithCustomToken(token).then((userCredential) => { .
Please help me.
I am new to Mean stack and have been struggling with this for quite a few days.
To give you an idea of what I am trying to make; I am creating a tagging tool that stores all requests and their tags in a collection called tags and then also storing all of the distinct tags into the Tagnames collection. I would like to understand why my MEAN stack api layer gives me a 404 error.
This error only occurs with my put method in the server.js file.
TaggingTool\server.js
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
tagsController = require('./server/controllers/tagscontroller');
mongoose.connect('mongodb://localhost:27017/STDBank');
app.use(bodyParser());
app.get('/', function (req, res) {
res.sendfile(__dirname + '/client/views/index.html');
});
app.use('/js', express.static(__dirname + '/client/js'));
//REST API
app.get('/api/tags', tagsController.list);
app.get('/api/tagnames', tagsController.listName);
app.post('/api/tags', tagsController.create);
app.put('/api/tagUpdate/:id', tagsController.update);
app.listen(3000, function() {
console.log('I\'m Listening...');
})
TaggingTool\server\models\tag.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TagSchema = new Schema({
request: String,
intentTag: String
}, {collection : "requests"});
module.exports = mongoose.model('Tag', TagSchema);
TaggingTool\server\models\name.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var nameSchema = new Schema({
name: String
}, {collection : "tags"});
module.exports = mongoose.model('TagName', nameSchema);
TaggingTool\server\controllers\tagscontroller.js
var Tag = require('../models/tag');
var TagName = require('../models/name');
module.exports.create = function (req, res) {
var tag = new Tag(req.body);
tag.save(function (err, result) {
res.json(result);
});
}
module.exports.listName = function(req, res){
TagName.find({}, function(err, results){
res.json(results);
});
}
module.exports.list = function (req, res) {
Tag.find({}, function (err, results) {
/*var arr = [];
for(var i = 0; i<results.length;i++){
if(results[i].intentTag){
console.log("enter if: ", results[i].intentTag);
}//end of if statement
else{
console.log("enter if: ", results[i].intentTag);
console.log("enters else statement ", arr);
arr.push({
_id : results[i]._id,
request : results[i].request
});
}//end of else statement
}//end of for loop
console.log("results ",arr);
*/
res.json(results);
});
}
module.exports.update = function(req, res){
console.log("Server side entered", res);
Tag.findByIdAndUpdate(req.params.id, {
$set: {
request: req.body.request,
intentTag: req.body.intentTag
}
}, function (err, tag){
if(err) res.send(err);
res.json(tag);
});
}
TaggingTool\client\js\controllers\tagsController.js
app.controller('tagsController', ['$scope', '$resource', function ($scope, $resource) {
var Tag = $resource('/api/tags');
var TagName = $resource('/api/tagnames');
var tagUpdate = $resource('/api/tagUpdate/:id');
Tag.query(function (results) {
$scope.tags = results;
});
TagName.query(function(results){
$scope.tagnames = results;
});
tagUpdate.query(function(results){
$scope.tags = results;
console.log("results: ", results);
});
//$scope.tags = [];
$scope.newtags=[];
console.log("tagReq", $scope);
$scope.newTag = function (index) {
console.log("newTag initiated");
var ntag = new tagUpdate();
console.log("_id: ", index);
var k = $scope.tagReq.request;
console.log("request: ", k);
var t = $scope.newTagName.tagname.name;
console.log("intentTag: ", t);
ntag._id = index;
ntag.request = $scope.tagReq.request;
ntag.intentTag = $scope.newTagName.tagname.name;
console.log("Tags: ", index);
$scope.ntag.$update({_id: index}, ntag);
}
$scope.createTag = function () {
var tag = new Tag();
tag.request = $scope.tagReq;
tag.intentTag = $scope.tagName;
tag.$save(function (result) {
$scope.tags.push(result);
$scope.tagName = '';
});
}
}]);
TaggingTool\client\js\app.js
var app = angular.module('taggingApp', ['ngResource'])
TaggingTool\client\views\index.html
<!DOCTYPE html>
<html ng-app="taggingApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tagging Tool </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<!-- Meetups View -->
<div ng-controller="tagsController">
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<caption><b><strong><em>Requests and their Tags</em></strong></b></caption>
<tr ng-repeat="tag in tags ">
<th ng-model="tagReq">{{tag.request}}</th>
<th>
<select ng-model="newTagName" ng-options="tagname.name for tagname in tagnames">
<option value="" >Select Tag</option>
</select>
<form ng-submit="newTag(tag._id)">
<input type="text" placeholder="Tag Name" ng-model="newTagName.tagname.name"></input>
<input type="submit"/>
</form>
<p>{{newTagName.tagname.name}}</p>
<p>{{tagReq.tag.request}}</p>
</th>
</tr>
</table>
<form ng-submit="createTag()">
<input type="text" placeholder="Tag name" ng-model="tagName"></input>
<button type="submit">Add</button>
</form>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-resource.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript" src="/js/controllers/tagsController.js"> </script>
</body>
</html>
I apologize for the terrible code and coding conventions, if anyone could help I would be extremely thankful.
I assume, this problem only occurs when you try to update from your Angular client? If so: Angular's $resource does not have an update method using PUT methods by default, see here.
You will need to define this manually, something along the lines:
$resource('/api/tagUpdate/:id', { id: '#_id' }, {
'update': { method: 'PUT' }
});
You can then use the resource's update method for performing your update.
Additional hint: With regards to REST conventions, I would not call the URL tagUpdate, but rather tags or something like this. The fact that you're updating is given by the HTTP method PUT already.
Okay I'm going to keep this as short as possible.
I've been studying Angular for a bit now and there's still a lot I need to learn, right now I'm trying to figure out how to connect end to end with headers in a service which is completely new to me as I've never done end to end integration.
The code below is provided from another stack overflow answer and what I want to know is how do I connect what they have with say dataService.js. This is all new to me so I'm trying to ask this the best way possible.
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<body ng-app="app">
<div ng-controller="gridController">
<!-- Initialise the grid with ng-init call -->
<div ui-grid="gridOptions" ng-init="GetGridData(urlList)">
</div>
</div>
<script src="Scripts/ng/angular.min.js"></script>
<script src="Scripts/ng-grid/ui-grid.min.js"></script>
<link rel="Stylesheet" type="text/css" href="Scripts/ng-grid/ui-rid.min.css" />
<script type="text/javascript">
var app = angular.module('app', ['ui.grid']);
app.controller("gridController",
["$scope", "$attrs", "$element", "$compile", "$http", "$q",
function ($scope, $attrs, $element, $compile, $http, $q)
{
$scope.urlList = "YourSourceUrl";
function fnGetList(url)
{
var deferred = $q.defer();
$http.get(url)
.success(function (data)
{
deferred.resolve(data);
})
.error(function (errorMessage)
{
alert(errorMessage);
deferred.reject;
});
return deferred.promise;
};
$scope.GetGridData = function (url)
{
console.log("In GetGridData: " + "Getting the data");
// Test Only - un-comment if you need to test the grid statically.
//$scope.loadData = ([
// {
// "UserName": "Joe.Doe",
// "Email": "Joe.Doe#myWeb.com"
// },
// {
// "UserName": "Jane.Doe",
// "Email": "Jane.Doe#myWeb.com"
// },
//]);
//return;
fnGetList(url).then(function (content)
{
// Assuming your content.data contains a well-formed JSON
if (content.data !== undefined)
{
$scope.loadData = JSON.parse(content.data);
}
});
};
$scope.gridOptions =
{
data: 'loadData',
columnDef:
[
{ field: 'UserName', name: 'User' },
{ field: 'Email', name: 'e-mail' }
]
};
}
]);
</script>
</body>
Provided from: How do I get data to show up in angular ui.grid from an $http request
The method I use is to pass the URL as an AJAX call and then wait for the data to get back after which I connect the JSON data to the ng-grid. Note that there will be a delay in getting the data back from the URL and you will have to have a timer that will keep checking for the data return begin valid.
function setCar(){
$.ajax({
type: "POST",
url: '/Test/ConfigConnect.json?details=&car='+car+'&id=1',
dataType: 'json',
success: function(data){
configData = data;
}
});}
The timer function that is part of the javascirpt is also given below.
var timer = setInterval(function() {
$scope.$apply(updatePage);
}, 500);
var updatePage = function() {
if (typeof configData !== 'undefined')
{
clearInterval(timer);
$scope.loadData = configData;
}
};
when I send this sample statement the verb is not displaying when I view the information in the LRS. The actor and other information is displaying correctly. Can someone tell me what I might be doing wrong? Thank you.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Statement</title>
<script src="js/tincan.js" type="text/javascript"></script>
<script type="text/javascript">
function init()
{
var tincan = new TinCan (
{
recordStores: [
{
endpoint: "https://lrs.adlnet.gov/xapi/",
username: "xapi-tools",
password: "xapi-tools",
allowFail: false
}
]
}
);
tincan.sendStatement(
{
actor: {
mbox: "mailto:myemailaddress#example.com"
},
verb: {
id: "http://adlnet.gov/expapi/verbs/attempted"
},
target: {
id: "http://tincanapi.com/activities/sending-my-first-statement"
}
},
function (err, result) {
//Handle any errors here. This code just outputs the result to the page.
document.write("<pre>");
document.write(JSON.stringify(err, null, 4));
document.write("</pre>");
document.write("<pre>");
document.write(JSON.stringify(result, null, 4));
document.write("</pre>");
}
);
}
</script>
</head>
<body onload='init()'>
Most likely nothing. Your statement could be "improved" by supplying a 'display' property and including one or more language code/value pairs inside of it so that the statement includes a "human readable" version of that object. I would think TinCanJS would have been doing that for you for that verb.
I'm coding a web app in html, AngularJS and REST (rest modified for my teachers).
My program should load participants in a select in the openning. But show i.e {{participants.name}} and not {{Jhon}}
The problem is at the moment that would load method "search".
Error:
"Error: Birthday.search is not a function
$scope.updateList#localhost:9000/birthday.js:26:1
#localhost:9000/birthday.js:31:5
e#localhost:9000/node_modules/angular/angular.min.js:36:313
Fe/this.$get
HTML:
<!DOCTYPE html>
<html lang="es" data-ng-app="birthdayApp">
<html>
<head>
<meta charset="utf-8">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="node_modules/angular/angular.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/estilo.css">
<script src="birthday.js"></script>
</head>
[...]
<body>
<div class="container-fluid" data-ng-controller="BirthdayControllers as birthday">
[...]
<select size="2" class="col-lg-12 col-md-12 col-xs-12">
<option data-ng-repeat="participant in participants | filter:filter"> {{participant.name}} </option>
</select>
[...]
The head its ok?
AngularJS
'use strict';
var app = angular.module("birthdayApp", [])
app.factory('Birthday', function($http) {
return function(errorHandler) {
this.search = function(callback, errorHandler) {
$http.get('/participants').success(callback).catch(errorHandler);
}
}
});
/* Controllers */
app.controller("BirthdayControllers", function($scope, Birthday) {
$scope.participants = null;
var errorHandler = function(error) {
$scope.notificarError(error.data);
};
$scope.updateList = function() {
Birthday.search(function(data) { //here stop, here the problem!
$scope.participants = data;
}, errorHandler);
}
$scope.updateList();
[...]
});
My factories look different. Here's how I do mine:
app.factory('Birthday', function ($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
Controller would look like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).error(function(data, status, headers, config) {
//handle the error
});
You need to return a factory object from the function not another function.
So modify your code like this:
app.factory('Birthday', function($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
It's better to handle the callbacks in the controller, so call the factory method like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).catch(function(error) {
$scope.notificarError(error.data);
});