Coulnd't get the output for angularJS in the browser - javascript

I am trying to use http.get and http.post method in angularJS. My html page and js file are as follows,
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="./../js/app.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
<p>Username : <input type="text" ng-model="name"></p>
<p>Quote : <input type="text" ng-model="quote"></p>
<button ng-click="ctrl.add();" name="button" type="button">Add</button>
<button ng-click="ctrl.retrieve();" name="button" type="button">Retrieve Price</button>
<p>The results here</p>
<table>
<tr>
<th>Quote</th>
<th>Price</th>
</tr>
<tr ng-repeat="q in quotes">
<td>{{q.quote}}</td>
<td>{{q.price}}</td>
</tr>
</table>
</div>
</body>
</html>
and
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 20000;
}])
app.controller('myCtrl', function($http, $scope) {
this.retrieve = function() {
$http.get('http://127.0.0.1:8302/api/stock-service/rest/stock/' + $scope.name)
.then(function (response) {
console.log('inside'+ response);
$scope.quotes = response.data;
}, function (response) {
console.log('came here');
});
}
this.add = function() {
var message = {
userName: $scope.name,
quotes: [$scope.quote]
}
$http.post('http://127.0.0.1:8302/api/db-service/rest/db/add', message)
.then(function(response) {
$scope.quotes = response.data;
}, function(response) {
console.log('error..');
});
}
});
But I couldn't find the output in the browser. Actually, I can see that request is sending through the particular uri. I am sure it is working in the back end at-least http.get method, but I have no idea why I am not getting the output.
In the command line I can see as follows,
2020-08-23 16:42:38.871 INFO 20060 --- [nio-8301-exec-6] y.quotes.query1v7.QuotesRequest : Sending request: https://query1.finance.yahoo.com/v7/finance/quote?symbols=GOOG
Thanks in advance.

Finally I could able to solve this problem by adding cross domain CORS extension in google chrome.
cross domain CORS extension
May be it can be a temporary solution.

Related

authentication with angular js / json

i tried to make login form with angular js
i have list of user in json file but i can't comapre with the input text from login form
User.json :
[{
"username": "user1",
"password": "pass1"
}, {
"username": "user2",
"password": "pass2"
}, {
"username": "user3",
"password": "pass3"
}, {
"username": "user4",
"password": "pass4"
}]
script.js
var app1 = angular.module('app1', []);
var app2 = angular.module('app2', []);
var app = angular.module('app', ['app1', 'app2']);
app1.controller('jsonCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
});
app2.controller('formCtrl', function($scope) {
$scope.login = function() {
if ($scope.username == 'test' && $scope.password == 'test') {
alert('valid username/password ' + $scope.username);
alert('user from json ' + $scope.users);
} else {
alert('invalid username/password ' + $scope.username);
}
};
});
index.html
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<body ng-app="app">
<div ng-controller="formCtrl">
<form name="form">
First Name:<br>
<input type="text" ng-model="username"><br>
Last Name:<br>
<input type="text" ng-model="password">
<br><br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div ng-controller="jsonCtrl">
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
</body>
</html>
the problem is replace if ($scope.username == 'test' && $scope.password == 'test') with anything compare with json
this my code : Plunker
You were using two different scopes across application. I moved all your markup under the same controller, so that is more simple manage the bindings.
Take a look at this plnkr
var app = angular.module('app', []);
app.controller('formCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
$scope.login = function() {
var u = $scope.users.filter((item) => {
return item.username == $scope.username;
});
if (u[0] && u[0].password == $scope.password) {
alert('correct');
} else {
alert('wr0ng');
}
};
});
<div>
<form name="form">
First Name:
<br>
<input type="text" ng-model="username">
<br> Last Name:
<br>
<input type="text" ng-model="password">
<br>
<br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div>
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
First of all, you should not authenticate user using clear text like that. Your server should do it with hashing table without knowing what is the real password.
Http.get is not synchronous which means that your application will continue its path without waiting for your data. In your plunker your formCtrl doesnt have access to jsonCtrl scope.
You should load your data in a service because it is initialised only once compared to the controller who are initialised everytime you load the page.
Finally you should start by looking at ui.router resolve, it allow you to load your data to your service before the page is displayed which will allow you to compare later.

Angular JS Json data

I am self educating myself in angular js. For this i have created a project modelled after an actual project in my job
All get operation work fine but POST is giving me issue
My controller.js
var ngapp = angular.module('ngWebApp', ['angularUtils.directives.dirPagination']);
ngapp.controller('ngIndexController', function ($scope, ngDashboardService) {
$scope.exportData = function (selectedDataList) {
var getData = ngDashboardService.AddReportAudit(selectedDataList)
getData.then(function (result) {
alert(result.data);
}, function () {
alert('Error in getting records');
});
};
});
My service.js
angular.module('ngWebApp').service("ngDashboardService", function ($http) {
this.AddReportAudit = function (dataList) {
var response = $http({
method: "POST",
url: "/Home/AddReportAudit",
data: {
'dataList': JSON.stringify(dataList)
}
});
return response;
};
});
My code of JasonResult in HomeController
public JsonResult AddReportAudit(List<ADTOWebSMARTT_SSOData> dataList)
{
if (dataList != null)
{
using (HRMSystemEntities contextObj = new HRMSystemEntities())
{
var itemList = dataList.Where(x => x.IsChecked == true).ToList();
itemList.ForEach(a => a.DateChecked = DateTime.Now);
contextObj.SaveChanges();
return Json(new { success = true });
}
}
else
{
return Json(new { success = false });
}
}
The problem occurs here
public JsonResult AddReportAudit(List dataList)
For some reason the dataList on reaching AddReportAudit become empty i.e. list has zero element. dataList has 30 records in controller.js and service.js.
I am not sure why that is happening. is there a parsing that I am missing when json data comes from angular to c#
You are actually sending an Object, so the data that reaches your public JsonResult AddReportAudit(....isAnObject), but you are expecting it to be a list. Just change your controller code to the snippet below, it should work.
angular.module('ngWebApp').service("ngDashboardService",
function($http) {
this.AddReportAudit = function (dataList) {
var response = $http({
method: "POST",
url: "/Home/AddReportAudit",
data:JSON.stringify(dataList)
});
return response;
};
});
Solution for angular 1. Place your web service url and change the json data format as per your need. It works.
<!DOCTYPE html>
<html>
<head>
<title>Angular HTTP service</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr>
<th>S No</th>
<th>Source Name</th>
</tr>
<tr ng-repeat="res in result">
<td>{{$index + 1}}</td>
<td>{{res.source_name}}</td>
</tr>
</table>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http){
$http.get("http://127.0.0.1:4000/all_source").then(function(res){
//console.log(res.data.result);
//console.log(res);
$scope.result = res.data.result;
});
});
</script>
</body>
</html>

Script makes bad request on its own (JS - TheMovieDb api)

I'am trying to make simple web application using TMDB api but I'm having trouble with some request.
I'am successfully connecting to its api and getting all needed data and displaying it nicely. Problem is when i load my Homepage which has poster_path of movie, i get all posters nicely and displayed but in chrome dev tools I can see there is one more extra request sent (not sent by me... at least not on purpose) and its failing and wracking my app.
Chrome displays following for bad request:
GET file:///C:/Users/Ivan/Documents/testProject/fmdb-fjume-movie-database/app/%7B%7BimageBaseUrl%7D%7D/%7B%7Bmovie.poster_path%7D%7D net::ERR_FILE_NOT_FOUND
Status: failed
Initiator: other
Here's my code for getting information and html:
Home view
<div class="well main-frame">
<h1>MY MOVIE DATABASE</h1>
<div class="row row-centered">
<div class="col-sm-2 col-centered" style="text-align:center;" ng-repeat="movie in movies | limitTo:2">
<img id="homeThumbnailImg" src="{{imageBaseUrl}}/{{movie.poster_path}}"></img>
{{movie.original_title}}
</div>
</div>
</div>
Home controller
'use strict';
angular.module('home', ['services'])
.controller('homeCtrl', ['$scope', '$q', 'api', 'globals', function($scope, $q, api, globals) {
$scope.imageBaseUrl = globals.getImageBaseUrl();
$scope.getData = function() {
$q.all([
api.discover('movie')
]).then(
function(data) {
$scope.movies = data[0].data.results;
//console.log(data[0].data.results);
},
function(reason) {
console.log(reason);
});
}
$scope.getData();
}]);
API
'use strict';
angular.module('services', [])
.constant('baseUrl', 'http://api.themoviedb.org/3/')
.constant('apiKey', 'myKey...')
.factory('api', function($http, apiKey, baseUrl) {
return {
discover: function(category) {
var url = baseUrl + 'discover/' + category + '?certification_country=US&certification.lte=G&sort_by=popularity.desc&api_key=' + apiKey;
return $http.get(url).success(function(data) {
return data;
});
},
search: function() {
},
...
Thank you all for your time!
You should change your img tag to look like this:
<img id="homeThumbnailImg" ng-src="{{imageBaseUrl}}/{{movie.poster_path}}"></img>
Note the ng-src attribute that replaces the src attribute. This will prevent the browser from trying to fetch the literal string {{imageBaseUrl}}/{{movie.poster_path}} before angular has a chance to eval that expression.

Simple angularJS GET function with localhost not working

I have a very simple Spring Rest backend that returns JSON data. The restful URL is working in my browser like this:
http://localhost:8080/abc/runlist
It returns data like so:
[
{"stock_num":"KOH19","damage":"Toronto (Oshawa)"},
{"stock_num":"AZ235","damage":"Toronto (Oshawa)"},
...
]
I have an independent html page that is not part of my web app. I just want to test to see if my angular code is getting the data and then looping through it.
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:8080/abc/runlist")
.success(function (response) {$scope.names = response.records;});
});
</script>
yo yo
</body>
</html>
Why is it not working? I came across something in Spring where you need to implement something called CORS. I did that like so but still nothing returned:
#Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain
chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,
DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
Try something like:
js:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:8080/abc/runlist")
.success(function (response){
$scope.names = records;
});
});
html:
<ul>
<li ng-repeat="x in records">
{{x}}
</li>
</ul>
more params html:
<ul>
<li ng-repeat="x in records">
{{x.myName}}
{{x.myNumber}}
</li>
</ul>
Hope I've been helpfull.
Try putting return in front of your $http.get
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
return $http.get("http://localhost:8080/abc/runlist").success(function (response) {
$scope.names = response;
});
});
</script>
then in your view use the dot notation to refer to the properties you want to display e.g.
{{x.stock_num}}
Got it! There were 2 fixes:
Firstly I had to implement the CORS filter and class in order not get this error:
org.apache.catalina.connector.ClientAbortException: java.io.IOException: An established connection was aborted by the software in your host machine
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:393)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:426)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:339)
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:418)
at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:406)
Secondly, a warning for example copiers! I had copied the simple example above from W3Schools, a great tutorial site as such:
$http.get("http://localhost:8080/abc/runlist")
.success(function (response) {$scope.names = response.records;});
Note the .records at the end of response. This was not needed. When I took it off, it worked.
More than likely it's being caused by your use of the file:// scheme. See the middle bullet on the linked question here for reasoning. Basically your origin is going to be null for file:// requests, which causes XmlHttpRequest to fail, which $http relies on.
try this:
$http.get("http://localhost:8080/abc/runlist")
.success(function (response, data, headers, status, config) {
$scope.names = response.names;
});
hope it will work. :)

Making an $http.get or $http.jsonp call in Angular.js

I was given the following code to use to get the data I need, but it is not working for me. What am I doing wrong here. I have tried many things from the Angular.js docs and other stack overflow posts, but nothing has worked for me.
someurl
header: Content-Type = application/json
Pass in the following json:
{
"userID": "SomeUSER",
"password": "SomePSWD"
}
Below is the code I am using and it is not working.
function getGroup($scope, $http) {
$http.get('SOMEURL?callback=JSON_CALLBACK&userID=SomeUSER&password=SomePSWD ').
success(function(data) {
$scope.group = data;
});
}
this angularjs demo app show how to use http.jsonp
var httpJsonDemoController = angular.module('HttpJsonDemo', []);
httpJsonDemoController.controller('DataController', ['$scope', '$http', function($scope, $http) {
$http.jsonp("http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Waseem%20Hero").
success(function(data) {
$scope.data = data;
$scope.name = data.name;
$scope.salutation = data.salutation;
$scope.greeting = data.greeting;
}).
error(function (data) {
$scope.data = "Request failed";
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div id="wrapper" ng-app="HttpJsonDemo">
<div ng-controller="DataController">
<pre ng-model="data">
{{data}}
</pre>
<input ng-model='name' />
{{name}}
<input ng-model='salutation' />
{{salutation}}
<input ng-model='greeting' />
{{greeting}}
</div>
</div>

Categories

Resources