Hello i need to show the response from a website (200, 404, etc) using REST services.
i have created a partial code but i dont know how show the result
This is js
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http ({
method: 'GET',
url: 'http:/www.google.com'
}).
then(function(response) {
$scope.greeting = response.data;
});
})
and this is html
<body>
<div ng-controller="Hello">
<p>Result = {{greeting.content}}</p>
</div>
</body>
</html>
Thanks for help.
You should really be putting your $http calls into a separate service and injecting that into the controller.
so something like this:
angular.module('demo')
.factory('greetingService', function($http) {
this.getGreeting = function() {
return $http ({
method: 'GET',
url: 'http:/www.google.com'
}).then(function(response) {
return response.data
});
}
};
Then inject the service into your controller and call greetingService.getGreeting and then set your $scope variable to the result.
Also make sure you have the proper headers in your request.
The response is a IHttpPromise<T> which extends IPromise<IHttpPromiseCallbackArg<T>>.
The interface for this looks like this:
interface IHttpPromiseCallbackArg<T> {
data?: T;
status?: number;
headers?: IHttpHeadersGetter;
config?: IRequestConfig;
statusText?: string;
}
So you can access what you need with:
response.status
With your code:
angular
.module('demo', [])
.controller('Hello', HelloController)
function HelloController($scope, $http) {
$http({
method: 'GET',
url: 'http://enable-cors.org'
})
.then(function(response) {
var text = "The status: " + response.status;
$scope.directResponse = response;
$scope.greeting = {content: text};
$scope.someVariable = text;
});
}
/*
var $http = angular.injector(["ng"]).get("$http");
$http.get("http://enable-cors.org/").then(function(response) {
console.log(response.status);
});
*/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="Hello">
<p>Status = {{directResponse.status}}</p>
<p>Result = {{greeting.content}}</p>
<p>Result = {{someVariable}}</p>
</div>
Related
I am new to this field so need help.I have to post data to API but i am unable to do this.Please help me and let me now the process.
API is: http://trendytoday.in/ers/api/DeviceAlarms
And JSOn format in which i have to send data is:
{
"ers": {
"agency_device_id": "1"
}
}
AngularJS provides the $http service, which has a method most. This can be used like:
var app = angular.module("app", []);
app.controller("HttpGetController", function($scope, $http) {
$scope.SendData = function() {
var data = {
"ers": {
"agency_device_id": "1"
}
}
$http.post('http://trendytoday.in/ers/api/DeviceAlarms', data)
.then(function(res) {
console.log(res);
}, function(err) {
console.error(err);
})
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="HttpGetController">
<button ng-click="SendData()">Submit</button>
<hr /> {{ PostDataResponse }}
</div>
This should be called from a controller or a service, and whichever you choose should have the $http service included as a dependency.
.controller('AppCtrl', function($scope, $http) {
$scope.ers = {
'agency_device_id' : ''
};
$scope.submit = function(){
var link = 'http://trendytoday.in/ers/api/DeviceAlarms';
$http.post(link, {ers: $scope.ers},{headers: {'Content-Type': 'application/json'} }).then(function (res){
$scope.mssg = res.data.ers.resMessage;
$scope.resp = res.data.ers.response;
How can i make the testservice factory return the result from the post request?, or make the app, factory update some $scope details thats within the overallcontroller ?
how can i update information within the overallcontroller from another controller?
app.factory('testservice', ['$http', 'auth', function($http, auth) {
var o = {
posts : []
};
o.test = function() {
return $http.post('/poster', null, {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
console.log(Data);
});
};
return o;
}]);
app.controller('overallController', ['$scope', 'posts', 'testservice', 'auth','$interval',
function($scope, posts, testservice, auth, $interval) {
$scope.data = {cash:"12879999",location:"test2",gang:"None","username":"test",
xp: 1290,
health: 100,
wanted: 30,
energy: 90};
var databackground = function() {
console.log("logging...");
var t = testservice.test;
console.log(t);
}
databackground();
$interval(databackground, 30000);
}]);
example html
<div class="main" ng-controller="overallController">
<section class="sides left" style="background:blue; height:100px;">
<ul>
<li ng-hide="isLoggedIn()">Logg inn</li>
</ul>
</section>
<div ng-controller"othercontroller">
// call made from some code here
</div>
</div>
Change your service to
o.test = function() {
return $http.post('/poster', null, {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).then(function(response){
return response.data;
});
};
And in your controller, do call the service, and get the results back in the promise:
testservice.test().then(function(data) {
$scope.data = data;
});
Read more about how to use promises here
You return the promise from your service, you would listen for that to resovle and get hold of your data.
Using $rootScope is heavy handed approach and should be used as a last resort. Services and event are preferable.
var databackground = function() {
console.log("logging...");
testservice.test()
.then(function (res) {
console.log(res.data); //Here is your data
});
}
EDIT: Your service should change slightly also. Firstly .success and .error are deprecated. Use .then and .catch instead.
If you wish to just return data out of your service just do:
o.test = function() {
return $http.post('/poster', null, {
headers: {
Authorization: 'Bearer ' + auth.getToken()
}
});
};
However if you want to transform the data in your service you can but ensure your return it or your controller wont get anything:
o.test = function() {
return $http.post('/poster', null, {
headers: {
Authorization: 'Bearer ' + auth.getToken()
}
})
.then(function (res) {
res.data.test = 'lol';
return res;
})
};
Try referencing $rootScope instead of $scope.
This will allow controllers and factories to interact with each other.
I have created a service and I have a responce, but I don't know how to use that responce into a controller.
The service that I have:
angular
.module('MyApp')
.service('telForm', function($http){
this.getAll = function(success, failure){
$http.get('https://service.com.mx/telehone')
.success(success)
.error(failure);
}
})
// the answer is
{
"telehone": "12121212",
"token": "760619"
}
The controller that I want to contruct: (moreless)
var1 = "telephone";
var2 = "token";
$http({
method:'POST',
url:"http://www.example-server.com/" + telephone + "/" + token + "/example",
data : {
phone: $scope.phone,
company: $scope.company,
contract: '1',
privacy: '1',
email: $scope.email
},
headers: {
'Content-Type': 'application/json'
}
})
Thanks in advance
First of all, the methods success and error are deprecated, as you can check on this deprecation notice:
Deprecation Notice
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
You can simply return a promise from your service and then do what you want in your controller, as the following:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope, telForm) {
$scope.response = '';
$scope.doGet = function() {
telForm.doGet().then(
function(response) {
$scope.response = 'success';
// $scope.services = response.data;
},
function(response) {
$scope.response = 'error';
});
}
$scope.doPost = function() {
$http({
method: 'POST',
url: "http://www.example-server.com/" + telephone + "/" + token + "/example",
data: {
phone: $scope.phone,
company: $scope.company,
contract: '1',
privacy: '1',
email: $scope.email
},
headers: {
'Content-Type': 'application/json'
}
});
}
})
.service('telForm', function($http) {
function doGet() {
// return promise from test
return $http.get('http://api.geonames.org/citiesJSON?');
}
return {
doGet: doGet
}
})
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
Response: <span ng-bind="response"></span>
<hr>
<button type="button" ng-click="doGet()">Request</button>
</body>
</html>
try something like this
.service('myService', ['$http', function ($http) {
var getAll = function (url, callback) {
$http.get(url)
.success(function (response) {
callback(response);
})
.error(function (err) {
callback(err);
})
}
return {
getAll:getAll
}
}]);
Then in your controller you call the service like so
.controller('myController', ['myService', function (myService) {
myService.getAll('http://...', function (response) {
// do something with the response
})
}]);
Without the ngcontroller alias, I can fetch the data. However, when with alias, I can't. What is my mistake here?
HTML tags:
<div style="padding: 10px" id="content_dv" ng-controller="displaytopic_ctrl as f">
<div class="topic_dv" ng-repeat="t in f.topic">
<p>{{ t.MEMBER_NAME }}</p>
</div>
</div>
in app.js:
.controller('displaytopic_ctrl', ['$http', function($http) {
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d){
if(d.t=='p'){
this.topic = d.topic;
}
}).error(
function(){
console.log('Query error');
});
}]);
Due to the way JavaScript closures work, the this variable that you are using in your success callback is not the controller. The most commonly used mechanism to solve this is to create an alias for the controller which you can reference inside your callbacks.
For Example:
.controller('displaytopic_ctrl', ['$http',
function($http) {
var controller = this;
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d) {
if (d.t == 'p') {
controller.topic = d.topic;
}
}).error(
function() {
console.log('Query error');
});
}
]);
angular.module('alertApp', [
'alertApp.controllers',
'alertApp.services'
]);
angular.module('alertApp.services', []).
factory('alertAPIservice', function($http) {
var alertAPI = {};
alertAPI.getAlerts = function() {
return $http({
method: 'JSONP',
url: 'http://localhost:50828/api/alert'
});
}
return alertAPI;
});
angular.module('alertApp.controllers', [])
.controller('mainController', function($scope, alertAPIservice) {
$scope.message = 'Hello Mid-World!';
$scope.alertsList = [];
alertAPIservice.getAlerts().success(function (response) {
$scope.alertsList = response;
});
});
My app runs fine without errors and I can see the $scope.message displayed on the page. In fiddler I can see that my api call returns a 200 message, but the success function is never called. What have I done wrong
UPDATE
I Changed to:
alertAPIservice.getAlerts().then(function successCallback(response) {
$scope.alertsList = response;
}, function errorCallback(response) {
console.log("turd");
});
And although I receieve a 200 in fiddler, the error callback is called. The response is from web api and is of type Ok();
You need to use the name of the callback as "JSON_CALLBACK".
Please refer your updated code as below -
angular.module('alertApp', ['alertApp.controllers','alertApp.services']);
angular.module('alertApp.services', []).factory('alertAPIservice', function($http) {
var alertAPI = {};
alertAPI.getAlerts = function() {
return $http.jsonp('https://angularjs.org/greet.php?name=StackOverflow&callback=JSON_CALLBACK');
//use &callback=JSON_CALLBACK' in url
}
return alertAPI;
});
angular.module('alertApp.controllers', [])
.controller('mainController', function($scope, alertAPIservice) {
$scope.message = 'Hello Mid-World!';
$scope.alertsList = "loading data";
alertAPIservice.getAlerts().then(function (response) {
$scope.alertsList = response.data;
},function(error,a,b){
$scope.alertsList = error;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="alertApp">
<div ng-controller="mainController">
{{message}}
<div>
<pre>{{alertsList|json}}</pre>
</div>
</div>
</body>
you can refer jsonp documentation here.
Hope this helps you!
Try this one ('then' instead of 'success' ):
alertAPIservice.getAlerts().then(function (response) {
$scope.alertsList = response;
});