How to create service and use it in controller - javascript

I am having a simple login form and I want to validate user upon successful HTTP request and it works fine. however, I've written all the code in the controller itself and I don't want that. i am new to angularjs so i have trouble creating service. so I need to create service for my logic. can anyone create service for the logic in the controller so that code works exactly same?
sample.html(for now it only prints username, password, and status code of response)
<html>
<head>
<script src="angular.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="mycontroller">
Username <input type="text" ng-model="login" /><br><br> Password <input
type="password" ng-model="pass" /><br>
<button type="submit" ng-click="myfunc()">Login</button>
<center>User name is {{ login }}, password is{{pass}}<br>
{{success.code}}
</div>
</body>
</div>
</body>
</html>
Controller
var app = angular.module("myapp", []);
app.controller("mycontroller", function($scope, $http, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
$http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: mydata
}).then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});

Super simple. First create a service, which injects $http module. Make a method you can call which returns promise from the $http module. In this example it's a get method.
app.service("ExampleService", function($http){
this.ExampleRequest = function(){
return $http.get('url');
}
});
Inject the service created above and you can call the functions you've defined in the service. Notice that the .then comes from the promise.
app.controller("exampleCtrl", function($scope, ExampleService){
$scope.onClick = function(){
ExampleService.ExampleRequest().then(function(data){
// Do something with data
});
}
});

Create a myService factory and create a function to send http req and return the response.
app.factory('myService', function($http) {
return {
httpReq: function(data) {
return $http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: data
})
}
}
});
Now call it from the controller.
app.controller("mycontroller", function($scope, myService, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
myService.httpReq(mydata)
.then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});

Related

angularjs data is not adding to service

I am using angularjs and ajax. I want to get the data from the webservice pass to controller. For passing the value to controller i am using holder (It's a factory method or service). It is working without webservice. But when i am calling data from web the data is getting correct but it is not updating to holder. My code is given below. When clicking the button "data1". I want to print the data from webservice in button name data2. It's not showing any error. And successfully data showing data in console but not adding data to holder.
index.html
<!DOCTYPE html>
<html ng-app="sharing">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ChildCtrl">
<button ng-click="increment() name="data1">+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2">
<h2>Second controller</h2>
<button ng-click="increment() name="data2">+</button>{{Holder.value}}
<button ng-click="" name="data3">+</button>{{Holder.name}}
</div>
</body>
</html>
script.js
// Code goes here
var app = angular.module('sharing', []);
var root="http://xxx.xxx.x.xx:60/Api";
app.factory('Holder', function() {
return {
value: 0,
name:""
};
});
app.controller('ChildCtrl', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
var jData1 = {};
jData1.BDMeetingId ="10003/2017";
var k=null;
console.log(JSON.stringify(jData1));
$.ajax({
type: "POST",
async: true,
url: root+"/Boardmeeting/BoardmeetingDetailsSevice",
data: JSON.stringify(jData1),
contentType: "text/plain",
dataType: "json",
crossDomain: true,
success: function (msg) {
k=msg;
$scope.BMNo=k.BMNo;
console.log(msg);
$scope.Holder.name=$scope.BMNo;
},
error: function (jqXHR, textStatus, errorThrown) {
},
});
};
});
app.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
if you are using angularjs so please avoid to use jQuery code please remove $.ajax and use $http or $resource its angularjs inbuilt provider.
for more details.
https://docs.angularjs.org/api/ng/service/$http
https://docs.angularjs.org/api/ngResource/service/$resource
I have got the answer when using the angularjs webservice instead of ajax webservice.
script.js
var app = angular.module('sharing', []);
var root="http://xxx.xxx.x.xx:60/Api";
app.factory('Holder', function() {
return {
value: 0,
name:""
};
});
app.controller('ChildCtrl', function($scope, Holder, $http) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
var jData1 = {};
jData1.BDMeetingId ="10003/2017";
console.log(JSON.stringify(jData1));
$http({
method: 'POST',
url: root+"/Boardmeeting/BoardmeetingDetailsSevice",
headers: {
'Content-Type': 'text/plain', /*or whatever type is relevant */
'Accept': 'application/json' /* ditto */
},
data: JSON.stringify(jData1)
}).then(function(response) {
console.log(response);
var k=response;
$scope.BMNo=k.BMNo;
console.log(response.data.BMNo);
$scope.Holder.name=response.data.BMNo;
},
function(response) { // optional
// failed
});
};
});
app.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});

How to implement angularjs async?

I am using AngularJS v1.5.8, My requirement is when i click the Next button it'll display 'Processing...' inside button as text before complete the operation, i have included the $q with my services to get the asynchronous facility, but not working. please see my below codes.
Service
mainApp.factory('PINVerificationServices', ['$http', '$rootScope','$q', function ($http, $rootScope) {
return {
IsPermitted: function (param) {
return $q($http({
url: '/Api/ApiPINVerification/IsPermitted/' + param,
method: 'POST',
async: true
}));
}
};
}]);
Controller
mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
$scope.SubmitText = "Next";
$scope.Next = function () {
$scope.SubmitText = "Processing...";
PINVerificationServices.IsPermitted($scope.PIN).then(function (result) {
$scope.SubmitText = "Next";
});
}
}
HTML
<div class="list-group list-group-sm">
<div class="list-group-item">
<input class="form-control" ng-model="PIN" placeholder="PIN" required id="PIN" name="PIN" type="text" />
</div>
</div>
<button type="submit" ng-click="Next()">{{SubmitText}}</button>
Try this:
return $http({
method: 'POST',
url: '/Api/ApiPINVerification/IsPermitted/' + param
});
Make below changes (from your requirement of nested $http).
In factory Use only $http, and no need of $rootScope as well, It should be like :
mainApp.factory('PINVerificationServices', ['$http', function ($http) {
return {
IsPermitted: function (param) {
return $http({
url: '/Api/ApiPINVerification/IsPermitted/' + param,
method: 'POST'
});
},
GetStudentInformationByPIN : function () {
return $http({
url: '/Api/ApiPINVerification/GetStudentInformationByPIN /',//your api url
method: 'GET'
});
}
};
}]);
In controller make use of $q.all() :
mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
$scope.SubmitText = "Next";
$scope.Next = function () {
$scope.SubmitText = "Processing...";
$q.all([PINVerificationServices.IsPermitted($scope.PIN),
PINVerificationServices.GetStudentInformationByPIN($scope.PI‌N),
//other promises
]).then(function (result) {
if(result[0].data){
$scope.SubmitText = "Next";
}
if(result[1].data){
// studentdata response handling
}
});
}
}

Factory "is not defined" in AngularJS

I'm a beginner in Angular world, and I can't work out why I'm still getting "not defined" error. Here is my code:
angular.module('dopasujApp').factory('getProducts', ['$http', function ($http) {
var dataFactory = {};
dataFactory.sort='ASC';
dataFactory.orderBy='PRODUCT_NAME';
dataFactory.search='a';
dataFactory.filters={};
dataFactory.filters.ATTRIBS=[46,25];
dataFactory.filters.SIZE=[165,40];
getProducts.listProducts = function() {
var request = $http({
method: "POST",
url: "http://******/backend/internalAPI.php?action=getListing&fit=1&limit=10&vendor=20",
headers: {
'Content-Type': 'application/json'
},
data: {
data: dataFactory
}
});
var products = angular.fromJson(request);
return products;
}
return false;
}]);
And here goes my controller (just for testing purposes now).
angular.module('dopasujApp')
.controller('MainCtrl', ['getProducts', '$scope','$rootScope',
function (getProducts, $scope,$rootScope) {
console.log(getProducts.listProducts())
}
]);
getProducts variable in factory is not defined. The name you used before is just informative name for angular
In your factory you are returning "false" as actual result. So angular treats your "false" as result.
It should look like that :
angular.module('dopasujApp').factory('getProducts', ['$http', function ($http) {
var dataFactory = {}, getProducts = {};
dataFactory.sort='ASC';
dataFactory.orderBy='PRODUCT_NAME';
dataFactory.search='a';
dataFactory.filters={};
dataFactory.filters.ATTRIBS=[46,25];
dataFactory.filters.SIZE=[165,40];
getProducts.listProducts = function() {
return $http({
method: "POST",
url: "http://******/backend/internalAPI.php?action=getListing&fit=1&limit=10&vendor=20",
headers: {
'Content-Type': 'application/json'
},
data: {
data: dataFactory
}
});
}
return getProducts;
}]);
Controller
angular.module('dopasujApp').controller('MainCtrl', ['getProducts', '$scope','$rootScope',
function (getProducts, $scope,$rootScope) {
getProducts.listProducts().then(function(res) {
console.log(res.data);
});
}
]);
EDIT:
Also note, that $http returns promise, but not actual query result, updated my example accordingly
try like this
var yourapp = angular.module('dopasujApp', []); //your defining your app first
yourapp.factory('getProducts', function ($http)
{
return {
//write your factory methods
};
});
you controller should be like below
yourapp.controller('MainCtrl', function PostController($scope, getProducts, $compile)
{
//here your controller methods
});

Angularjs Ajax get sending headers

I'm new to angularjs, and im using a service for my http requests.
one of the rest api's i need to send key value pairs in the header.
username: foo
password: bar
how do i do it using the http request format i have in my service. (i'm aware i need to pass an argument in the function i don't how to go about it and what object format)
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
this.CheckIfUserExists = function () {
return $http.get($rootScope.endPoint + '/user/email_token');
};
}
...
//in the controller
UserService.CheckIfUserExist()
.success(function (data) {
console.log(data);
//handler
}).
error(function(error) {
//handler
});
Example from the doc
you need know what kind of auth. you can use post for example.
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).success(function(){...}).error(function(){...});
In your case:
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
this.CheckIfUserExists = function () {
var req = {
method: 'POST',
url: 'http://example.com'
data: { 'username': 'foo', 'password': 'bar' }
};
return $http(req);
}
}

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

I have the following code in the controller.js,
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = dataService.getData();
});
But, I think I m probably making a mistake with CORS related issue. Can you please point me to the correct way to make this call? Thanks much!
First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.
I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.
For simplicity, here's your same code re-written with a function callback provided by the calling controller:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
Now, $http actually already returns a $promise, so this can be re-written:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.
I suggest you use Promise
myApp.service('dataService', function($http,$q) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
deferred = $q.defer();
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, we can resolve promise and we can access it in controller
deferred.resolve();
}).error(function(){
alert("error");
//let the function caller know the error
deferred.reject(error);
});
return deferred.promise;
}
});
so In your controller you can use the method
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.
No need to promise with $http, i use it just with two returns :
myApp.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data;
}).error(function(){
alert("error");
return null ;
});
}
});
In controller
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
Try this
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.
So you need to use what we call promise. Read how angular handles it here, https://docs.angularjs.org/api/ng/service/$q. Turns our $http support promises inherently so in your case we'll do something like this,
(function() {
"use strict";
var serviceCallJson = function($http) {
this.getCustomers = function() {
// http method anyways returns promise so you can catch it in calling function
return $http({
method : 'get',
url : '../viewersData/userPwdPair.json'
});
}
}
var validateIn = function (serviceCallJson, $q) {
this.called = function(username, password) {
var deferred = $q.defer();
serviceCallJson.getCustomers().then(
function( returnedData ) {
console.log(returnedData); // you should get output here this is a success handler
var i = 0;
angular.forEach(returnedData, function(value, key){
while (i < 10) {
if(value[i].username == username) {
if(value[i].password == password) {
alert("Logged In");
}
}
i = i + 1;
}
});
},
function() {
// this is error handler
}
);
return deferred.promise;
}
}
angular.module('assignment1App')
.service ('serviceCallJson', serviceCallJson)
angular.module('assignment1App')
.service ('validateIn', ['serviceCallJson', validateIn])
}())
Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.
The service:
MyApp.service('getData',
[
'$http',
function($http) {
this.getQuote = function(ticker) {
var _url = 'https://www.google.com/finance/info?q=' + ticker;
return $http.get(_url); //Simply return the promise to the caller
};
}
]
);
The controller:
MyApp.controller('StockREST',
[
'$scope',
'getData', //<-- the service above
function($scope, getData) {
var getQuote = function(symbol) {
getData.getQuote(symbol)
.success(function(response, status, headers, config) {
var _data = response.substring(4, response.length);
var _json = JSON.parse(_data);
$scope.stockQuoteData = _json[0];
// ticker: $scope.stockQuoteData.t
// last price: $scope.stockQuoteData.l
// last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
// last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
})
.error(function(response, status, headers, config) {
console.log('### Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
});
};
getQuote($scope.ticker.tick.name); //Initialize
$scope.getQuote = getQuote; //as defined above
}
]
);
The HTML:
<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>
At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.
When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.
myApp.service('serverOperations', function($http) {
this.get_data = function(user) {
return $http.post('http://localhost/serverOperations.php?action=get_data', user);
};
})
myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {
serverOperations.get_data(user)
.then( function(response) {
console.log(response.data);
}
);
})

Categories

Resources