How to get data from RESTful web service? - angularjs

I developed one RESTful web service. The link return json code, like these:
{"status":"itPassed","dest":"/elk2/kr659p/home"}
Now I want to display these data in my screen.
View:
<!doctype html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular-resource.min.js"></script>
<script src="../controllers/webservice.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{greeting.status}}</p>
<p>The content is {{greeting.dest}}</p>
</div>
</body>
</html>
My Controller
angular.module('myApp', []).controller('Hello', function ($scope, $http) {
alert(1);
$http.get('http://9.124.130.197:2020/PatchAdminTool/rest/service/getstatus/123').
success(function(data) {
alert(2);
$scope.greeting = data;
alert(data);
});
});

no errors in console? because that's not really how you write a controller in angularJS.
you should have something like
angular.module('mymodule', []).controller('Hello', function ($scope, $http) {
$http.get('http://9.124.130.197:2020/PatchAdminTool/rest/service/getstatus/123').
success(function(data) {
alert(data);
$scope.greeting = data;
alert(data);
});
});
by the way, does the alert actually show something?

Did you try to place breakpoints?
Open the Chrome Debugger - Place the following breakpoints:
on the $http.get line - see if you are reaching it.
on the alert(data) line - see if the data contain what you expected.

Related

Angular http get no response from api

I am trying to get any information with Angular from the local api that I have created in Ruby, Sinatra platform. I am sure that the api is running on the port 4567 since I can see the data if i access m it directly through web interface. When I do that I see this (just next to the number 0 there is like a small arrow so it is possible to minimize the details of the object):
0
id "1"
name "Company-A21"
address "Gany-A11"
If I want to see RAW data I get this:
[{"id":"1","name":"Company-A21","address":"Gany-A11"}]
On the "other side" I am running apache2 and this HTML file:
<!doctype html>
<html >
<head>
<title>Hello AngularJS</title>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{company.id}}</p>
<p>The content is {{company.name}}</p>
</div>
</body>
</html>
And the hello.js:
angular.module('demo', [])
.controller('Hello', function($scope, $http){
$http.get('http://localhost:4567/api/v1/companies/2').
then(function(response) {
$scope.company = response.data;
});
});
Why I can not see response?
I just started to practice Angular and I stuck here...
Your data is an array of objects so you'd output it like: {{company[0].id}}
You probably followed an example using ng-repeat which would look something like this:
<div ng-repeat="company in companies">
<p>The ID is {{company.id}}</p>
<p>The content is {{company.name}}</p>
</div>
https://jsfiddle.net/ojzdxpt1/21/
Use ng-init to execute your get request. Implement your api call under a method:
angular.module('demo', [])
.controller('Hello', function($scope, $http){
$scope.getCompany = function(){
$http.get('http://localhost:4567/api/v1/companies/2').
then(function(response) {
$scope.company = response.data;
});
}
});
and use it in ng-init:
<!doctype html>
<html >
<head>
<title>Hello AngularJS</title>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello" ng-init="getCompany()">
<p>The ID is {{company.id}}</p>
<p>The content is {{company.name}}</p>
</div>
</body>
</html>

Using AngularJS or how to call rest services from CustomApp

I would like to know if it is possible to add angularjs to the custom app in Rally, or as alternative how to call REST services from a Rally Custom app. Can someone help me with this? Thanks in advance.
Best Regards
Here is an example of making a WS API call from an Angular app from inside Rally's custom page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myapp">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<div ng-controller="MyController" >
<button ng-click="myData.doClick(item, $event)">Send AJAX Request to Rally</button>
<br/>
Data from server: {{myData.fromServer}}
</div>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myData = {};
$scope.myData.doClick = function(item, event) {
var responsePromise = $http.get("https://rally1.rallydev.com/slm/webservice/v2.0/defect");
responsePromise.success(function(data, status, headers, config) {
$scope.myData.fromServer = data.QueryResult.Results[0];
console.log(data);
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
}
} );
</script>
</div>
</body>
</html>
Using external CDN within app is expected to produce Mixed Content error if accessing over http. It works if https is used. Here is the first query result (a defect from my current project) is returned.

AngularJS creating new $scope that subtracts two $scopes consumed from a JSON array

I am very very new to AngularJS and programming and I am sure this is a basic question but I am having a difficult time finding our resources in how to achieve subtracting two $scope values consumed from a JSON file ($scope.carrierDiff). I would appreciate any help you can provide.
<!doctype html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body >
<div ng-controller="SiteCtrl">
<ul ng-repeat="site in sites">
<li>{{site.ID}}</li>
<li>{{carrierDiff}}</li>
</ul>
</div></body>
<script>
var app = angular.module("MyApp", []);
app.controller("SiteCtrl", function($scope, $http) {
$http.get('JSON/getsamplesitesCopy.json').
success(function(data, status, headers, config) {
$scope.sites = data;
$scope.carrierDiff = $scope.sites.Carrier - $scope.sites.Carrier2;
}).
error(function(data, status, headers, config) {
// log error
});
});
</script>
</html>
No need to calculate this separately
$scope.carrierDiff = $scope.sites.Carrier - $scope.sites.Carrier2;
You just have to do this...
<body >
<div ng-controller="SiteCtrl">
<ul ng-repeat="site in sites">
<li>{{site.ID}}</li>
<li>{{site.Carrier - site.Carrier2}}</li>
</ul>
</div>
</body>
With my limited knowledge of what is coming back from the file you are retrieving, it seems as though you are referencing the JSON data incorrectly. You need to reference $scope.sites OR data, not a hacked up version of both. If the structure of data looks like this:
data = {Carrier: 5, Carrier: 4}
Then you would reference Carrier like so:
data.Carrier1
So when you move data to $scope.sites, you are referencing the JSON in data and it would be referenced without the need to point out that it came from data
$scope.sites.Carrier1
So you code should look like so:
http://plnkr.co/edit/nnfewy?p=preview
<!doctype html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body >
<div ng-controller="SiteCtrl">
<ul ng-repeat="site in sites">
<li>{{site.ID}}</li>
<li>{{carrierDiff}}</li>
</ul>
</div>
<script>
var app = angular.module("MyApp", []);
app.controller("SiteCtrl", function($scope, $http) {
$http.get('JSON/getsamplesitesCopy.json').
success(function(data, status, headers, config) {
$scope.sites = data;
$scope.carrierDiff = $scope.sites.Carrier - $scope.sites.Carrier2;
}).
error(function(data, status, headers, config) {
// log error
});
});
</script>
</body>
</html>
Another item to remember, you should have you <script> in the head or in the body, not outside. See the modification in the code above.

Using angular-local-storage Inside a Service?

I am trying to use the angular-local-storage module (https://github.com/grevory/angular-local-storage), version 0.2.2 (according to bower) in a service within my application. I seem to be having issues with it when I call it within a service, but it works fine when I put it inside a controller.
I have it configured like this:
angular.module('myApp', [ 'LocalStorageModule' ])
.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('test')
.setStorageType('localStorage');
})...
And then in my service, I have it like this (simplified, for testing purposes):
angular.module('myApp')
.service('UserService', [ 'localStorageService',
function(localStorageService) {
return {
save: function() {
localStorageService.set('user', 'me');
}
};
}]);
This code yields an error of:
TypeError: localStorageService.set is not a function
On the other hand, if I place the exact same code into a controller (indeed, the controller who calls this service), everything works as expected. Does angular-local-storage not work within services?
Thanks in advance!
It does work for me with minor tweaks. See below code snippet.
angular.module('myApp', [ 'LocalStorageModule' ])
.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('test')
.setStorageType('localStorage');
})
.service('UserService', [ 'localStorageService',
function(localStorageService) {
return {
save: function() {
localStorageService.set('user', 'me');
}
};
}])
.controller('MainCtrl', function($scope, UserService){
$scope.test = function(){
console.debug('save called');
UserService.save();
};
});
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div ng-controller="MainCtrl">
<button ng-click="test()">Test</button>
</div>
<script type="text/ng-template" id="home.html">
Lorem ipsum
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="bower_components/angular-local-storage/dist/angular-local-storage.js"></script>
</body>
</html>

How to update controller variable with 'ng-model' AngularJS?

I am trying to get user input through a text box using ng-model, and append to a base URL for a http.get call as follow;
index.html:
<html ng-app='vidRoute'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Search Video</title>
<link rel="stylesheet" href="app/css/custom/main.css">
<link rel="stylesheet" href="app/css/custom/responsive.css">
</head>
<body>
<div id='mainwrapper'>
<div id='header' ng-controller="searchController">
<input type="text" id="searchTxt" ng-model="append">
Search Video
</div>
<div id="poster">
<div ng-view></div>
</div>
</div>
<script type="text/javascript" src="app/javascript/vendor/jquery-2.1.1.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-route.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-resource.js"></script>
<script type="text/javascript" src="app/javascript/vendor/angular-mocks.js"></script>
<script type="text/javascript" src="app/javascript/custom/searchcontroller.js"></script>
<script type="text/javascript" src="app/javascript/custom/vidRoute.js"></script>
</body>
</html>
searchcontroller.js
'use strict';
var vidcontrol = angular.module("vidcontrol", []);
vidcontrol.controller("vidcontroller", ['$scope', '$http', function($scope, $http) {
$http.get('http://api.themoviedb.org/3/tv/airing_today?api_key=d5e87524383e2872a9555990b268dc5b').success(function(response) {
$scope.results = response.results;
});
}]);
vidcontrol.controller('searchController', ['$scope', '$http',
function ($scope, $http) {
var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
// var searchTxt = $('#searchTxt').val();// this works fine when used
var searchUrl = url + append; //$scope.append also logs 'undefined' on the console
$http.get(searchUrl).success(function (response) {
$scope.searchResults = response.results;
});
}]);
but I'm not getting any response. when I log searchUrl on console, I could see that append was not updated according to value from text box. I'm quite new to Angular and I can't figure out what I'm doing wrong. What should I do to fix this?
Now, I see the issue. When controller loaded, it executes controller code. That mean REST query runs before view is built. That is reason you see undefined problem. Solution is to define a method in controller which will be invoked when you click "Search Video".
Update view
Search Video //Look at ng-click
Update Controller:
vidcontrol.controller('searchController', ['$scope', '$http',function($scope, $http) {
var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
$scope.search = function(){ // Look at here, Defined a method to invoke on "Search Video" link click
var searchUrl = url + $scope.append;
$http.get(searchUrl).success(function(response) {
$scope.searchResults = response.results;
});
};
} ]);

Resources