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

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

Related

How do I convert a controller http call to a Service/factory pattern that takes in a parameter

I have a controller that is calling http.get, http.push and http.post methods.
I am learning angularjs and have found that it's best to call your http.get in your service file. I am able to do that with a simple http.get, but get confused with a http.get by id or http.get/http.post which takes a parameter:
My current controller looks like this
angular.module("app-complaints")
.controller("clcontrol", clcontrol);
function clcontrol($routeParams, $http, $scope) {
$http.get(baseURL + "/api/complaints/" + $scope.complaintCase + "/checklists")
.then(function (cl) {
//success
$scope.index = 0;
$scope.cl = [];
$scope.cl = cl;
}
I want to separate it out like this
controller.js
angular.module("app-complaints")
.controller('clcontrol', function ($http, $scope, $q, Service, $timeout) {
....
getCL();
function getCL(){
Service.getCl()
.success(function(cl){
$scope.cl = [];
$scope.cl = cl;
}
service.js
angular.module("app-complaints")
.factory('Service', ['$http', function ($http) {
Service.getCL = function () {
return $http.get(urlBase + "/api/complaints/" + complaintCase + "/checklists")
};
};
Simple. Make a factory that accepts parameters.
var app = angular.module("MyApp", [ /* dependencies */]);
app.factory("SharedServices", ["$http", function($http) {
return {
getItems: function(url, parameters) {
return $http.get(url, {
//optional query string like {userId: user.id} -> ?userId=value
params: parameters
});
},
postItem: function(url, item) {
var payload = {
item: item
};
return $http.post(url, payload);
},
deleteItem: function(url, item) {
var payload = {
item: item
};
return $http({
url: url,
data: payload,
method: 'DELETE',
});
}
// ETC. ETC. ETC.
// follow this pattern for methods like PUT, POST, anything you need
};
}]);
Use the service in your controller:
app.controller("MainCtrl", ["$scope","SharedServices", function($scope, SharedServices) {
//do things with the shared service
$scope.postMyThings = function() {
SharedServices.postItems('path/to/api', itemsArray).then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
};
$scope.getMyThing = function() {
SharedServices.getItems('path/to/api/get').then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
}
}]);

How to pass form parameters to Rest using angularjs services?

I try to pass my form parameters to java rest backend but i cant.
controller
$scope.addNewThing = function () {
Myservice.addNew($scope.name);
};
service
addNew: function (name) {
var Foo = $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {}}
});
var results = Foo.save({name: name}, function(data) {
results = data;
});
return results;
}
//also tried this version of code
addNew: function(name) {
return $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {name: 'test'}}
});
}
rest backend function
#POST
#Produces("application/json")
#Path("/addNew")
public Response addNew(#FormParam("name") String name) {
try {
//when i check name here it is always null
...
}
}
I can't pass the html form parameter to java rest backend via angular. Also tried to change #FormParam to #QueryParam but it didn't work.
Did you set the default content-type on $http POST requests?
app.config(function($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
});
I don'n know how to receive params value in java but I can show how to pass params from angular service. when you will want to pass params then you should use :paramsName in your URL path.
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {name: '#name'}, {
'post': {method: 'GET'}
});
return addNewItem.post({name: name});
}
or if you don't use /:name in your url you should pass in your header
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {}, {
'post': {method: 'GET', headers: { 'name': name }}
});
return addNewItem.post({name: name});
}
NB: your Content-Type should be application/json
You can try this:
CONTROLLER
$scope.addNewThing = function () {
yourService.addNew($scope.name);
};
SERVICE
angular.module('MyApp')
.service('yourService',['$http', function ($http) {
this.addNew = function (data) {
$http({
url: 'YourURL',
method: 'POST',
data: data, // your $scope.name
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function (response) {
console.log('good');
})
.error(function (response) {
console.log('error');
});
};
}]);
JAVA REST API
#POST
#Path("/addNew")
#Consumes("*/*")
public Response addNew(String name) {
// use here your String name
}
Using jQuery params solved my problem
Here is the correct way:
Myservice.addNew().save($.param({
name:$scope.name
}),function(data){
console.log(data);
},function(err){
console.log(err);
});
I can pass the parameters like this with $resource service.

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

How to take the resposne from one ng controller to another ng cntroller

I am a newbie to ng. Here, I have a scenario where I need to take the response received from success to another controller. I have tried the below code but I am not able to achieve my target.
CODE:
$scope.received = function(){
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
//The data received here I need t take to mydataController
$location.path('/success');
})
when('/success', {
templateUrl: 'ngtemplates/success/success.html',
controller: 'mydataController'
}).
app.controller('mydataController',
[ '$scope', '$http',function($scope, $http,$location) {
//I want the success data here in some function
}]);
Please, help me
you can use a service for your purpose.
SERVICE :
myApp.factory('dataService', function() {
var _data;
this.setData = function(someData) {
_data = someData; // better use angular.copy() function
}
return {
data : _data;
}
});
HTTP CALL :
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
//The data received here I need t take to mydataController
// before using dataService, make sure you inject it to the controller
dataService.setData(data);
$location.path('/success');
});
CONTROLLER
app.controller('mydataController',
[ '$scope', '$http',function($scope, $http,$location, dataService) {
//I want the success data here in some function
var someData = dataService.data;
}]);
You have 2 solutions. you can make a Service or use events.
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
$rootScope.$broadcast('dataReceived', data);
$location.path('/success');
});
In mydataController:
$rootScope.$on('dataReceived', function(e, data) {
// do something with the data
}
Or you can make a service to share the data between the two.
angular.module('demo').service('myDataService', function() {
this.data = null;
this.setData = function(data) {
this.data = data;
}
});
in the controller:
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
myDataService.setData(data);
$location.path('/success');
});
In mydataController:
$scope.something = myDataService.data;

setup $http url from .properties file in angularjs

I have some services in my App.
loginApp.factory('urlService', function() {
return {
baseUrl : function(){
return 'http://localhost:8080/myAppName'
}
}
});
consume this service by one another services.
loginApp.factory('loginServices', function($http,urlService) {
return {
loginAuth : function(aut,resp){
return $http({
method: 'GET',
url: urlService.baseUrl()+'auth',
}).success(function(result) {
return result;
});
}
}
});
I want configure http://localhost:8080/myAppName from a .properties file which is present on application root.
You can do some thing like this
angular.module('app.properties', []).provider('properties', function() {
var resource;
$.ajax({
url: 'properties.json',
dataType: 'json',
async: false,
success: function(data) {
resource = data;
}
});
this.properties= resource;
this.$get = function() {
return this.properties;
};
});
Then use this provider in you controller/services to access the properties
angular.module('loginApp', ['app.properties']).factory('urlService', function(properties) {
return {
baseUrl : function(){
return properties.baseUrl;
}
}
});
And your properties.json should be like
{
"baseUrl" :"http://localhost:8080/myAppName"
}
NB : I have used jquery ajax to load the properties.json because it should not be an async call, so I set async: false
$.ajax({
url: 'properties.json',
dataType: 'json',
**async: false**,
success: function(data) {
resource = data;
}
});
I think the best option in that case would be to create a service that then can be injected and in that service pull the config file and assign content to a returned variable (hope it makes sense so far)
Although that will leave you with possible race issues when i.e. your loginService will be called before config was loaded but if you make a good use of promises all this will be trivial for you

Categories