how to post data in API in angularJS in ionic app - angularjs

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;

Related

Angularjs $http GET json data not displayed

I'm trying to get json data through json server. I create an angularjs application and generate a fake REST API with json server at http://localhost:3000/records which return json data successfully.
But with $http service I cannot catch the data !
this is my service and controller code:
Service code: contact.service.js
`(function () {
var app = angular.module("contactApp");
app.service("contactSvc", contactSvc);
function contactSvc($http) {
$http({
method: "GET",
url: "http://localhost:3000/records/"
}).then(function mySuccess(response) {
var msg = "succès !";
this.res = response.data.records;
});
};})();`
code of the controller : contact.controller.js
`(function (){
var app = angular.module("contactApp");
app.controller("contactCtrl", contactCtrl);
function contactCtrl(appName,contactSvc) {
this.applicationName = appName;
this.contacts = contactSvc.res;
this.errmsg = contactSvc.msg;
this.selectContact = function (index) {
this.selectedContact = this.contacts[index];
};
}})();`
and finaly code of index.html:
`<div ng-controller="contactCtrl as ctrl">
<ul class="list-group">
<li ng-repeat="contact in ctrl.contacts" ng-click="ctrl.selectContact($index)">
{{contact.name.first +" "+contact.name.last}} </li>
</ul>
</div>`
Many thanks for your help
You should return promise from contactSvcfunction and when's resolved it should return response.data from that function.
var contactSvc= angular.module("contactApp").service("contactSvc", ['$http', function($http) {
return {
getcontacts: function() {
return $http.get('http://localhost:3000/records/')
.then(function(response) {
console.log("coming from servicejs", response.data);
return response.data;
});
}
};
}]);
In your controller you should call the service function and use .then function to get call it when the getResponders service function resolves the $http.get call and assign the data to $scope.gotData
Code
myService.getcontacts().then(function(data){
this.contacts = data.records;
});

AngularJs $http response from a website

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>

Angularjs moving logic from the controller

How can I move this function from the controller into a separate file?
It might be a simple question but I tried to do that with services and factories but I keep doing something wrong regarding dependency injection or the syntax of the service or factory.
This is the controller:
angular.module("myApp", [])
.controller('myAppCtrl', function ($scope, $http) {
(function() {
//the function to be moved
//do somthing
})();
$scope.data = {};
$http.//......do something else
});
plunkr: (Replaced real API link at request of OP)
HTML:
<div ng-app="myApp">
<div ng-controller="myAppCtrl">
<ul>
<li ng-repeat="product in data.products" ng-bind="product.name"></li>
</ul>
</div>
</div>
Javascript:
angular.module("myApp", [])
.constant("dataUrl", "https://some-link.com")
.controller('myAppCtrl', function($scope, corsService) {
$scope.data = {};
corsService.getData().then(function(data) {
$scope.data.products = data;
}).catch(function(error) {
$scope.data.error = error;
});
});
angular.module("myApp")
.factory('corsService', function($http, dataUrl) {
return {
getData: getData
}
function corsRequestEnabler() {
//Enable CORS requests
};
function getData() {
corsRequestEnabler();
return $http.get(dataUrl)
.then(function(response) {
console.log('Response', response);
return response.data;
}, function(error) {
return error
})
}
});
var app=angular.module("myApp", []);
app.controller('myAppCtrl', function (corsService, $scope, $http, dataUrl ) {
corsService();
app.factory('corsService' ,function($http){
var data = {};
$http.get(dataUrl)
.success(function (data) {
data.products = data;
console.log(data);
})
.error(function (error) {
data.error = error;
});
return data;
});
});

Running factory based on condition

I have a log in screen that when the user enters the correct credentials will be able to get JSON data. For now I don't have a real API link. I'm just using dummy JSON data from a script file. The loginCtrl will pass parameters to the 'dummydata' factory which will make a 'GET' request. On success, the factor will pass the JSON data to the 'useData' function in the factory. This function in the factory is what all the controllers in my ng-view use.
The problem that I am having is that all the other controllers are calling 'dummyData.dashboardsData' and getting undefined because no one has logged in to pass data to that function. How can I prevent controllers (for example, navCtrl) from calling the factory until someone has logged in?
This is my index file:
<body ng-app="ciscoImaDashboardApp" ng-style="{'background-image': backgroundImg}" ng-controller="loginCtrl">
<login></login>
<div ng-view></div>
<menu></menu>
</body>
This is my factory:
angular.module('ciscoImaDashboardApp').factory('dummyData', ['$q', '$http', function($q, $http) {
var apiServices = {};
apiServices.login = function(user,password,callback) {
$http({method: 'GET', url: 'scripts/services/dummydata.js'})
.success(function (response) {
dataStatus = response.success;
apiServices.useData(response);
callback(dataStatus);
})
.error(function(error) {
console.log("There was an error: " + error);
});
};
apiServices.useData = function(response) {
var data = response.data;
apiServices.dashboardsData = data;
}
return apiServices;
}]);
This is my navCtrl:
angular.module('ciscoImaDashboardApp')
.controller('navCtrl', function($scope, navService, $location, dummyData) {
var data = dummyData.dashboardsData;
});
This is my loginCtrl:
angular.module('ciscoImaDashboardApp')
.controller('loginCtrl', function ($scope, $rootScope, dummyData, $location) {
$scope.login = function() {
var user_email = $scope.email;
var user_password = $scope.password;
dummyData.login(user_email, user_password, function (dataStatus) {
if (dataStatus) {
console.log("Success!");
$scope.loggedIn = true;
$location.path('/welcome');
} else {
console.log("Error");
}
});
}
});

Simple Angular app - cannot get $http success/then to fire

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;
});

Resources