Error while using get request in AngilarJS - angularjs

I have some JSON data in stored in file: weeklyData.json (which is inside folder json) that I want to display in console using GET request, but I'm getting result undefined.
My app.js file consist both approaches for GET request but the result remains same: undefined.
HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crazy Data Component</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="plugins/bootstrap_Plugin/css/bootstrap.min.css">
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1>{{msg}}</h1>
<script src="plugins/bootstrap_Plugin/jquery.min.js"></script>
<script src="plugins/bootstrap_Plugin/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="js/app.js"></script>
<!-- <script src=""></script>-->
</body>
</html>
app.js
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope, $http) {
$scope.msg = "Something";
$http({
method: 'GET',
url: 'json/weeklyData.json',
headers: {
'Content-type': 'application/json'
}
}).then(function (response) {
console.log(response.data)
}, function (error) {
console.log(error.data)
})
})
// $http.get('json/weeklyData.json').success(function (data) {
// $scope.dub = data;
// console.log('$scope.dub', $scope.dub);
// })
//})
Can someone suggest something?

Your code is working.. check below snippet,
Your sample json is not accessed. check your url .
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope, $http) {
$scope.msg = "Something";
$http({
method: 'GET',
url: 'https://www.w3schools.com/angular/customers.php',
headers: {
'Content-type': 'application/json'
}
}).then(function (response) {
console.log(response.data)
}, function (error) {
console.log(error.data)
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crazy Data Component</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="plugins/bootstrap_Plugin/css/bootstrap.min.css">
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1>{{msg}}</h1>
<script src="plugins/bootstrap_Plugin/jquery.min.js"></script>
<script src="plugins/bootstrap_Plugin/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="js/app.js"></script>
<!-- <script src=""></script>-->
</body>
</html>

Related

Consistently Getting Error: $injector:nomod Module Unavailable When I Load My App

I think it has something to do with the way my files are ordered but I can't figure out which ones are causing the problem.
angular.module('app')
.controller('langCtrl', function($scope, languageService){
$scope.submit = function(model) {
console.log(model);
languageService.analyzeDocument(model)
}
});
<html lang="en" ng-app="app" class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>WIT</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="images/computer.ico"/>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="app.css">
</head>
<body ng-controller="langCtrl">
<div class="header">
RecommendHER
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app.js"></script>
<script src="languageService.js"></script>
<script src="langCtrl.js"></script>
</body>
</html>
I put the index.html file and my controller in the snippet. I also have a service on the save level as app.js and the controller file. Here is the code:
angular.module('app')
.service('languageService', function($resource) {
var apiUrl = 'http://xxx.compute-1.amazonaws.com';
var languageResource = $resource(apiUrl + {}, {
analyzeDocument: {
method: 'POST',
url: apiUrl + '/analyze_document?file=:text'
},
analyzeWord: {
method: 'POST',
url: apiUrl + '/recommend?word=":word"'
}
});
return {
analyzeDocument: function(data) {
return languageResource.analyzeDocument({data:text}).$promise;
},
analyzeWord: function(data) {
return languageResource.analyzeWord({data:word}).$promise;
}
};
});
Here is my app.js file:
angular.module('app', [
]);
You need to add empty dependencies to your module,
angular.module('app',[])
EDIT
Change the order in index.html to make your module load first,
<script src="app.js"></script>
<script src="languageService.js"></script>
<script src="langCtrl.js"></script>
Have you defined the 'app' module with two parameters yet:
angular.module('app', []).run(function() {});
The one parameter version expects app to already exist in order for things to be included as part of the module.
Also, ensure that the app.js file is loaded first.

How to read value from json data and display in angularjs

I want to display name in string format but Main.html page is not reading value from session.json page.so please help me
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope, Session) {
$scope.name = 'World';
$scope.session = Session;
});
app.run(function(Session) {}); //bootstrap session;
app.factory('Session', function($http) {
var Session = {
data: {},
saveSession: function() { /* save session data to db */ },
updateSession: function() {
/* load data from db */
$http.get('session.json')
.then(function(r) { return Session.data = r.data;})
}
};
Session.updateSession();
return Session;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Hello {{name}}</h1>
Welcome,
<pre ng-bind='session.data.username | json'></pre>
</body>
</html>
This is session.json page but in $http.get('session.json') it is not reading value from this page .
{ "username": "John Smith" }
how to read string from the json page to main.html and display
See the following code,
$http({
"method": "get",
"url": "session.json"
});
Here session.json and this file( the file in which this $http call is present) are in the same folder.

data to read my json file in IONIC

This world is sad to cry , am blocked for two hours with a problem that i couldnt define ,i can't retrieve data from my json file ,everything in my code seems correct.
This is my factory:
'use strict';
angular.module('starter.services')
.factory('userService',function ($http) {
return{
getUsers:function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
return response.data;
});
}
}
});
and this controller :
'use strict';
angular.module('starter.controllers', ['starter.services'])
.controller('UsersCtrl', function($scope,userService) {
$scope.Users = [];
userService.getUsers().then(function (data) { $scope.Users= data.data; }); });
});
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/UserControllerIonic.js"></script>
<script src="js/UsersServiceIonic.js"></script>
</head>
<body ng-app="starter" ng-controller="UsersCtrl">
<ion-view>
<div class = "list" >
<a class = "item" ng-repeat = "user in Users">
<h2>{{user.nom}}</h2>
</a>
</div>
</ion-view>
</body>
</html>
Thank you in advance
SOLUTION
i solved the problem by :
1- adding in the config.xml the permission <allow-navigation href="http://*/*"/>
2-installing cordova-plugin-whitelist ionic plugin add cordova-plugin-whitelist
3-add control-allow-origin extention to chrome :https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en-US
and finally : specifying the type of data returned by the back-end controller by adding this code to my Global.asax in Application_start method :config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
config.Formatters.Remove(config.Formatters.XmlFormatter);
hope this helps someone
You don't want to resolve your $http call inside factory.
JS:
angular.module('app',[])
.controller('MainCtrl', function($scope, MyService){
var url = "http://jsonplaceholder.typicode.com/users";
MyService.getData(url).then(function(res){
console.log(res.data);
$scope.data = res.data;
});
})
.service('MyService', function($http){
return {
getData: function(url){
return $http.get(url);
}
}
})
HTML:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in data">{{item.name}}</li>
</ul>
</body>
</html>
The issue is that you are resolving the promise in service with the value response.data, and again expecting the resolved value to have data property. Change your service code as below:
'use strict';
angular
.module('starter.services')
.factory('userService',function ($http) {
return {
getUsers: function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
return response;
});
}
}
});
Or simply return the promise as below:
'use strict';
angular
.module('starter.services')
.factory('userService',function ($http) {
return {
getUsers: function(){
return $http.get("http://localhost:26309/api/User/getAll/");
}
}
});

Angular Posting not sending

This is my index.html page:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My AngularJS App</title>
<link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
<link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
<link rel="stylesheet" href="app.css">
<script src="bower_components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="HomeCtrl">
<form ng-submit="sendPost()">
<label>Input id</label>
<input type="text" ng-model="id" required/>
<button type="submit">Submit</button>
</form>
{{response}}
</div>
</body>
</html>
Here's my app.js:
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [])
.controller('HomeCtrl', function($scope, $http) {
$scope.id = "";
$scope.response = "";
$scope.sendPost = function() {
var userDetails = [{"userId":"23848348", "type":"CUSTOMER"}];
var request = {
method: 'POST',
url: 'http://thisisatest.testhost.com/userInfo',
headers: {
'Content-Type': 'application/json',
'id':$scope.id
},
data: $.param({
json: JSON.stringify({
'code':'8388',
'userDetails': userDetails
})
})
}
$http(request)
.success(function(data, status, headers, config){
/*called for result & error because 200 status*/
if (data.result) {
$scope.response = data.result;
} else if (data.error) {
//handle error here
}
})
.error(function(data, status, headers, config){
/*handle non 200 statuses*/
});
}
})
Here's what the json request body is supposed to look like:
{
"code":"8388",
"userDetails": [
{
"userId": "23848348",
"type": "CUSTOMER"
}
]
}
But when i input an id in the textbox and hit submit i dont see anything printed in the response area. Any idea what I did wrong here?
I found the issue. The data portion of the request should just be:
data: {
'code':'8388',
'userDetails': userDetails
}

Custom URL using Angular ngResource

I would like to know the best practice for connecting with my API as it works as following:
GET -> products/list/latest -> return list of latest products
GET -> products/list/popular -> return list of popular products
GET -> products/list/trending -> return list of trending products
and then when I want a detail of the each product, it is just:
GET -> products/:id
I got the following code in my services.js:
.factory('ProductService', function ($resource) {
return $resource('http://domainname.com/api/products/:product',{product: "#product"});
})
But I really don't know how to access these custom URLs. Can I use the ngResource for that?
Thanks!
Please see here https://docs.angularjs.org/api/ngResource/service/$resource
you can add custom action to ngResources
ie:
var app = angular.module('app', ['ngResource']);
app.factory('ProductService', function($resource) {
var actions = {
'latest': {
method: 'GET',
url: 'api/products/latest '
},
'popular': {
method: 'GET',
url: 'api/products/popular'
},
'trending': {
method: 'GET',
url: 'api/products/trending '
}
};
var ProductService = $resource('/api/products/:productId', {ProductId: '#id'}, actions);
return ProductService;
});
app.controller('MainCtrl', function($scope, ProductService) {
$scope.name = 'World';
ProductService.latest();
ProductService.popular();
ProductService.trending();
ProductService.query();
ProductService.get({id: 1});
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-resource.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>

Resources