Call a function inside an object in AngularJS factory - javascript

angular.module('snswMock').factory('snswService', ['$http','$location' ,
function ($http, $location ) {
'use strict';
return {
getData: function(jsonData){
var jsonString = JSON.stringify(jsonData);
var serviceUrl = getServiceUrl();
$http({
url: serviceUrl,
dataType: 'string',
method: 'POST',
data: jsonString
}).success(function(response){
alert ("Success");
}).error(function(error){
alert ("Save company!");
});
},
getServiceUrl :function(){
var host = $location.host();
if (host === 'localhost') {
return $location.protocol() + '://' + host + ':9000/services/insert';
} else {
return $location.protocol() + '://' + host + '/services/insert';
}
}
}
}
]);
Hi am very new to the angular
this is my service
I am calling getServiceUrl inside getData function i am getting the below error
angular.js:11706 ReferenceError: getServiceUrl is not defined
can anyone please help me how can I call the method. is there any other way is there to call web service by passing a string as post request?

The controller where you are trying to access this service, do below things.
Inject this service in the controller.
Call this service like below
snswService.getServiceUrl();

You need to use this context to access a global object function -> this.getServiceUrl(). In your case myFactory is the object and inside your object all functions are globally accessible inside your object scope by using this context.
angular.module('snswMock').factory('snswService', ['$http', '$location', function($http, $location) {
'use strict';
var myFactory = {
getData: function(jsonData) {
var jsonString = JSON.stringify(jsonData);
var serviceUrl = this.getServiceUrl(); //modified
$http({
url: serviceUrl,
dataType: 'string',
method: 'POST',
data: jsonString
}).success(function(response) {
alert("Success");
}).error(function(error) {
alert("Save company!");
});
},
getServiceUrl: function() {
var host = $location.host();
if (host === 'localhost') {
return $location.protocol() + '://' + host + ':9000/services/insert';
} else {
return $location.protocol() + '://' + host + '/services/insert';
}
}
}
return myFactory;
}]);

Related

defining functions in angularjs constants

controller.js
angular.module('app.main')
.controller('MainCtrl', function ($scope, currentUser, addAPI) {
$scope.form = {};
$scope.subdomain = currentUser.domainName;
$scope.add = function () {
addAPI.addAdmin(localStorage['token'], $scope.subdomain, $scope.form, onSuccess, onError);
};
take the details from the form and pass token and subdomain(took from current userDatService)
addAPI.js
angular.module('app.main').factory('addAPI', function ($resource, $http, Constant) {
var adminAPI = function () {
this.addAdmin = function (token, domain, dataObj, sucCall, errCall) {
$http({
method: 'POST',
url: Constant.API.prefix + domain + Constant.API.postfix + '/client/admin',
headers: {
'Token': token
},
data: dataObj
}).then(handleResp).catch(handleResp);
};
return new adminAPI;});
sending data to API URL
constants.js
angular.module('app.constants', [])
.constant('Constant', {
'API': {
prefix: 'http://api.',
postfix:'.dev.education.in/v1/academy-api/api/v.1.0'
}
});
1.I want to have a function in constants.js which accepts user or subdomain and returns URL?
2.is it the right way to format a base_url or any suggestions on improving.
3.I need to define a perfect base_url with prefix + domain + postfix + ...
I'm new to angularJs and Javascript and i tried my best to get a solution but functions are not working with constants
It may be a better method to put your constants in a vanilla javascript file and load them onto the stack (via html) before any angular-related scripts are loaded. That way they will already be in the global namespace and you can simply refer to them anywhere.
e.g.
Constant.js
var API = {
prefix: 'http://api.',
postfix:'.dev.education.in/v1/academy-api/api/v.1.0'
}
index.html
<script src="Constant.js"></script>
<script src="factories/addAPI.js"></script>
addAPI.js
angular.module('app.main').factory('addAPI', function ($resource, $http, Constant) {
var adminAPI = function () {
this.addAdmin = function (token, domain, dataObj, sucCall, errCall) {
$http({
method: 'POST',
url: API.prefix + domain + API.postfix + '/client/admin',
headers: {
'Token': token
},
data: dataObj
}).then(handleResp).catch(handleResp);
};
return new adminAPI;});

Call Angularjs Controller from Jquery

I am working on a project where I have two Controller
register and Login.
how do I call Login Controller n success function of Registration.
This is my Controller
.controller('LoginCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk) {
$scope.user = {};
$scope.$parent.clearFabs();
$timeout(function() {
$scope.$parent.hideHeader();
}, 0);
ionicMaterialInk.displayEffect();
$scope.Login = function(user) {
Loginfunction($scope.user.username);
};
});
and this is my registration Jquery Function which stores the data on the Server
function Registerfunction(user) {
//alert(user.fname);
var dataString = 'firstname=' + user.fname +
'&lastname=' + user.lname +
'&email=' + user.email +
'&password=' + user.password;
$.ajax({
type: "POST",
url: "http://seller.example.com/registerapp.php",
data: dataString,
cache: true,
success: function(msg) {
alert('saba');
//window.location.href="index.html";
angular.element($("#login"))
.scope()
.callFromJquery('I Called You ! Angular !');
}
});
return false;
}
when I run this, It's giving me an error angular.element(...).scope(...) is undefined
How to solve this issue

How to test an http request in my case?

I have a service like this.
It is simply just make a http get request.
angular.module('myApp').service('TESTService', ['$http',
function($http) {
var request = function(url) {
return $http({
method: 'GET',
url: url
});
};
return {
get: function(url) {
return request(url);
}
};
}
]);
Within my controller, I have called the service
TESTService.get('/api/product' + id).success(
function(result) {
console.log(result)
}
);
I need to write the unit test for it
describe('test here', function () {
var testCtrl, scope, httpBackend, testService;
// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _TESTService_) {
scope = _$rootScope_.$new();
httpBackend = _$httpBackend_;
testService = _TESTService_;
testCtrl = _$controller_('testCtrl', {
$scope: scope
});
it('should return http data', function() {
var productData = {
data: [
{
obj: {
id:'123'
}
}
]
}
httpBackend.expectGET('/api/product/' + id).respond(productData);
TESTService.get('/api/product/' + id).
then(function(data) {
var result = data;
})
httpBackend.flush();
expect(result).toEqual(productData)
});
}));
After running the test, I got
Error: Unexpected request: GET /api/product/undefined
How do I write the test to make sure it passes? Any ideas? Thanks a lot!
Your variable "id" seems to be undefined. If you throw in
var id = 123;
before this line:
httpBackend.expectGET('/api/product/' + id).respond(productData);
It would call /api/product/123 instead.
So maybe you were looking for this in the first place:
httpBackend.expectGET('/api/product/' + productData.data[0].obj.id).respond(productData);
TESTService.get('/api/product/' + productData.data[0].obj.id).
And so on... Hope it helps!
Try putting single quotes around the object that's passed into $http, i.e. $http({method: 'GET', 'url', url});
angular.module('myApp').service('TESTService', ['$http',
function($http) {
var request = function(url) {
return $http({
method: 'GET',
'url': url
});
};
return {
get: function(url) {
return request(url);
}
};
}
]);

Angular factory ajax call on every route change

I have a factory where I have a function getExpenseList which does an ajax call which queries the expense table and gives me the result.
Now I have two routes, 1 which is listing of expenses which is pushing the expense through the above function and the second route is an add. When I do a route change and come back to the listing page, the ajax call is made again. Ideally I should be able to store the expense object on the first ajax call and then reference the same object till someone is manually refreshing the browser.
please help me on this. Here is my factory code. Ideally I would like to refer to this.expenses if the data is present.
admin.factory('expenseFact', ['$http', function($http) {
var expense = {};
this.expenses = "";
expense.getExpenseList = function() {
this.expenses = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
});
return this.expenses;
};
return expense;
}]);
And here is my controller code
admin.controller('expenseLandCtrl', function ($scope,$rootScope,expenseFact) {
$scope.pageTitle = $rootScope.pageTitle;
expenseFact.getExpenseList().then(function (data) {
$scope.expenses = data.data;
});
});
admin.controller('expenseAddCtrl', function ($scope,$rootScope,expenseFact) {
$scope.pageTitle = $rootScope.pageTitle;
});
your factory will be like this
admin.factory('expenseFact', ['$http', function($http) {
return {
getExpenseList: function() {
var expense = {};
this.expenses = $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
});
return this.expenses;
}
}
}]);
and you can call it from controller same way and it wont call it automatically.
btw i recommend use of promises.
below is same code with use of promise
admin.factory('expenseFact', ['$http', '$q'. function($http, $q) {
return {
getExpenseList: function(){
var deferred = $q.defer();
$http({method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).
then(function(response) {
deferred.resolve(response.data);
}, function(response) {
deferred.reject(response.status)
});
return deferred.promise;
}
}
}]);
You need to get the expenses once when the factory is loaded for the first time;
admin.factory('expenseFact', ['$http', function($http) {
var expenses = null;
$http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "GET",
url: base_url + "rest/expenses"
}).success(function (exp) {
expenses = exp;
}); // get the expenses when the factory is loaded
return {expenses: expenses};
}]);
What this does is that it makes the expenses return from the factory refer to the one-time ajax call to get the expenses.

Set up Relative Path for a all $https Call in AngularJS

I am new angularJS.
I have make call more then 10 $http request using services in my project.
One service code is given below.
loginApp.factory('serviceAuth', function($http) {
return {
fnLoginAuth : function(aut,resp){
return $http({
method: 'GET',
url: 'http://localhost:8080/myProjectname/serviceName',
}).success(function(result) {
return result;
});
}
}
});
I want http://localhost:8080/myProjectname/ this part of url is configurable or use a variable instead of this URL.
In my applications written in AngularJS, I just put the variable in the $rootScope.
app.run(['$rootScope',
function($rootScope) {
$rootScope.serverRoot = '/projectname/public';
}
]);
And append it to the services.
this.addTask = function(data) {
return $http.post($rootScope.serverRoot + '/task/create', data);
}
Why don't you add another service that returns the base URL?
app.factory('urlService', function() {
var url = "";
return {
setUrl : function(newUrl){
url = newUrl;
},
getUrl : function(){
return url;
}
}
});
and use it like this:
app.run(function(urlService) {
urlService.setUrl('http://localhost:8080/myProjectname/');
})
loginApp.factory('serviceAuth', function($http, urlService) {
return {
fnLoginAuth : function(aut,resp){
return $http({
method: 'GET',
url: urlService.getUrl() + 'serviceName',
}).success(function(result) {
return result;
});
}
}
});

Categories