AngularJS : How to inject a service into a factory - angularjs

I have a REST backend which provides a hashmap of API methods. This allows the front end to use a keyname to map to the API method instead of needing to know the entire REST url.
Ex:
{
CHARGE.GET_CHARGE_INFO: /provider/charge/getChargeInfo/{{providerId}}/{{chargeId}}
CHARGE.LIST_CHARGES: /provider/charge/listCharges/{{providerId}}
CHARGE.LIST_TYPES: /provider/charge/listTypes
}
There is a service which is responsible for loading the hashmap from the REST API.
app.service('preloader', function ($http, globals, $interpolate, $q) {
var self = this;
var endPointsList = $http.get(globals.apiPath + globals.endPointsPath, {}).success(function (data) {
self.endPoints = data;
});
return {
endPointsList: endPointsList,
getResourceEndPoint: function( endPoint ){
if (!self.endPoints[endPoint]) {
// To avoid misleading errors
throw ("Endpoint not found. \r\nEndpoint: " + endPoint + "\r\nFound: " + self.endPoints[endPoint]);
}
// reformat
return globals.apiPath + self.endPoints[endPoint].replace(/{{([^}]+)}}/g, ":$1");
}
};
I'm trying to write a $resource which uses this service, but the problem is when the service is injected into the factory, it has not yet been initialized and consequently calls to the method to retrieve the endpoint throw errors.
app.factory('providerFactory', ['$resource', 'preloader',
function ($resource, preloader) {
return $resource( "", null,
{
"getTypes" : {
method: 'GET',
url: preloader.getResourceEndPoint('PROVIDER.LIST_TYPES')
},
"get": {
method: 'GET',
url: preloader.getResourceEndPoint('PROVIDER.GET_PROVIDER_INFO'),
params: {
providerId: '#providerId'
}
}
}
);
});
Error Msg:
TypeError: Cannot read property 'PROVIDER.LIST_TYPES' of undefined
at Object.getResourceEndPoint (http://localhost:8888/client.git/build/app.min.js:3:8967)
If I step through the code, I see that the factory's preloader.getResourceEndPoint() calls are calling the service before the service has completed its initialization of the endPointsList.
What can I do to avoid this problem? Do I have to use a $q promise? It seems like overkill for something like this. If so then I have to wonder if this is even the right approach to get something like this to work, but I'm not sure what approach to use.
I'm still learning AngularJS so I'm not entirely sure of the correct way to proceed. Ive inherited this code so if it seems that it is convoluted/complicated for nothing, I'd appreciate insights on how to improve it.

Related

Mock $http with configuration parameters

I'm applying some tests in an existing AngularJS application in order to ensure it's correct behaviour for future changes in the code.
I am pretty new with Jasmine & Karma testing, so I've decided to start with a small and basic service which performs an http request to the backend, and waits for the result with a promise, nothing new.
Here's the service method to test:
function getInformedConsent(queryParameters) {
var def = $q.defer(),
httpParameters = {
url: ENV.apiEndpoint + '/urlResource',
method: 'GET',
params: queryParameters,
paramSerializer: '$httpParamSerializerJQLike'
};
$http(httpParameters)
.then(
function (response) {
def.resolve(response);
},
function (error) {
def.reject(error);
}
);
return def.promise;
}
And here my test:
it('getInformedConsent method test', function() {
$httpBackend.expectGET(/.*\/urlResource?.*/g)
.respond(informedConsentJson.response);
var promise;
promise = InformedconsentService.getInformedConsent(informedConsentJson.queryParameters[0]);
promise
.then(function(response) {
console.log(response);
expect(response).toEqual(informedConsentJson.response);
});
$httpBackend.flush();
});
informedConsentJson as you can supose, is a fixture with input and the expected output.
Reading AngularJS documentation, I decided to use $httpBackend, because it's already a mock of $http service, so I thought it could be useful.
The problem is that somewhere in the code, someone is broadcasting a "$locationChangeStart" event and executing
$rootScope.$on('$locationChangeStart', function (event,current,old) {
/* some code here */
});
in app.js.
I'm not trying to change the URL, i'm just trying to get some data from the mocked backend.
I asume that is because I'm not using $http mock ($httpBackend) as it should be used.
Anyone can help me with $http with configuration JSON mock?
It's freaking me out.
Thank you all in advance for your time and your responses

Store domain in one place in angular js service

I have the following example method in angular service:
function send(data) {
return $http({
method: 'POST',
url: 'https://test.domain/test/send',
data: $httpParamSerializerJQLike(data)
});
}
The domain that is https://test.domain/test is the same for all the services in my app. I do not want to write it every time in every services. I can abstract it in a constant and inject it in every service but I wonder if there is more clever solution. Is it possible to store the domain part in an interceptor or any other suggestions are welcome. Please provide code examples as I am quite new to angular. Thanks
I'd say rather than abstracting the values out into a constant, you should abstract the $http call into a service. Then you can just inject that service into all of your other services in place of $http. For example:
angular.module('myApp').factory("myHttp", ["$http", function ($http) {
return function (config) {
config.url = "https://test.domain/test" + config.url;
return $http(config);
};
}]);
So effectively what this service is doing is proxying calls to $http, but prepending your common URL to the beginning - this would allow you to change your example code to:
function send(data) {
return myHttp({
method: 'POST',
url: '/send',
data: $httpParamSerializerJQLike(data)
});
}
Of course, this is just one example of how you could do an abstraction like this - the myHttp service could take any form you like, depending on what would be most convenient for you. I think this is a better solution than using an interceptor in this case, as it allows you to pick and choose when you use it, rather than it being applied to every single HTTP request.
create an interceptor and on requests change the url.
angular.module('app').factory('domainInterceptorService', [
function () {
var request = function (config) {
config.url = 'https://test.domain/' + config.url;
}
return config;
}
return {request: request};
});

how to have angularJS post data to MVC controller which redirects to a view

I am posting some data to an MVC action method using AngularJS. This action method will either show its backing view or redirect to another page. Currently all that is happening is the data is getting posted but the redirect is not happening via MVC. I am getting this done using angular's window.location method. I want to know if there is a better way or if I need to post differently using Angular.
On page A I have angular scripts posting data to page B like below:
serviceDataFactory.POST('http://localhost:1234/home/B', someData, pageConfig).then(function () {
//on success
window.location = 'http://localhost:1234/home/Index';
},
function() {
//on error
window.location = 'http://localhost:1234/home/B';
});
This is my service factory
app.factory('serviceFactory', function($http, $q) {
var service = {};
//POST
service.POST = function (url, postData, conf) {
var d = $q.defer();
$http({
method: 'POST',
url: url,
data: postData,
config: conf
}).success(function(data) {
d.resolve(data);
}).error(function(error) {
d.reject(error);
});
return d.promise;
}
return service;
}
);
On Page B I want to redirect to another page. This is my page B in MVC
[HttpPost]
public ActionResult B(string someData)
{
//recieve string someData and perform some logic based on it
.
.
.
if(boolCondition)
return RedirectToAction("Index", "Home");
else
return View();
}
Here once Angular posts to the action method B, it executes all the code all the way till the if(boolCondition) statement. Since I am unable to have that redirect affected via MVC, I do that in Angular itself using the success or error block that the promise returns to.
I want to know if there is a better way to do this or if I am doing something wrong here or if this is the only acceptable way. How do I get angular to hand-off to the MVC action method and let further redirects continue from there only?
You should not use the .success() / .error() pattern with $http, because this has been deprecated. Instead, use then() with two arguments, the first argument being the success function and the second being the error function.
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 do not need to promisify the result of $http, because $http returns a promise. Just return $http from your service.
app.factory('serviceFactory', function($http, $q) {
var service = {};
//POST
service.POST = function (url, postData, conf) {
return $http({
method: 'POST',
url: url,
data: postData,
config: conf
});
}
return service;
});
Your Page A controller will work the same as before with this new simplified code. At the server, be sure to emit a 500 http status code in cases where you want to trigger the
function() {
//on error
window.location = 'http://localhost:1234/home/B';
}
to run. The 500 in the headers of the response will cause the AngularJS promise to run the second function in your controller.

PUT and POST Angularjs

I have an Ionic project with a WCF RESTful service, I want to be able to Insert and Update data. I can already view data with GET method but can't find anything on the internet for PUT and POST. How would I be able to accomplish this?
GET Method
$scope.selectedDist= function() {
$http.get("http://192.168.1.113/Service1.svc/GetAllComp")
.success(function(data) {
var obj = data;
var ar = [];
angular.forEach(obj, function(index, element) {
angular.forEach(index, function(indexN, elementN) {
ar.push({CompID: indexN.CompID, CompName: indexN.CompName});
$scope.districts = ar;
});
});
})
.error(function(data) {
console.log("failure");})
};
Post methods I tried
#1
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http.post("http://192.168.1.113/Service1.svc/GetAllComp", ar)
.success(function(data)
{
console.log("data inserted successfully")
})
.error(function(data)
{
console.log("Error")
})
#2
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http ({
url : "localhost:15021/Service1.svc/TruckDetails" ,
Method : "POST" ,
headers : {
'Content-Type' : 'Application / json; charset = utf-8'
},
Data : ar
})
Also Would I need to make a POST or PUT method on my Service as well or can I use the GET methods?
You can use a get method, in combination with a querystring to post and put data but that is not what it was designed for and should be avoided for several reasons such as security.
That being said, it is not that difficult to use post and put in angular and in the following , rather naive service , you can see all that is required to do is passing your data in the service function you're invoking.
.service('MyService', function($http) {
this.postMethod = function(data) {
return $http.post('http://my.url', data);
};
this.putMethod = function(id, data) {
return $http.put('http://my.url/' + id, data);
};
}
So that in your controller you can inject and invoke the service methods with the $scope data that needs to be stored.
After taking a look at your attempts you seem to be using the same url for both get and post: "http://192.168.1.113/Service1.svc/GetAllComp" which actually leads me to believe you haven't thought about implementing these methods on your server. Can you confirm this?
Apart from that, it is always usefull to look at statuscodes when trying to send requests because they provide a great deal of information about the nature of the error that occurs. You can investigate that in either your console or an external program such as Fiddler.
P.S.
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.

Get response header in then() function of a ngResource object's $promise property after resource resolved?

I'm willing to retrieve the response header of a resource request, cause I've put pagination information and something else in it rather than the response body, to make the REST api clear.
Though we can get it from the success / error callback like below:
Object.get({type:'foo'}, function(value, responseHeaders){
var headers = responseHeaders();
});
Where 'Object' is my resource factory service.
Further, when I'm trying to make the route change after required resources resolved, I've tried this:
.when('/list', {
templateUrl: 'partials/list.html',
controller: 'ListCtrl',
// wait for the required promises to be resolved before controller is instantialized
resolve: {
objects: ['Object', '$route', function(Object, $route){
return Object.query($route.current.params).$promise;
}]
}
})
and in controller, just inject "objects" instead of Object service, because it's resolved and filled in with real data.
But I got problem when I try to get headers info from the "objects" in controller.
I tried objects.$promise.then(function(data, responseHeaders){}), but responseHeader was undefined.
How can I change the $resource service's behavior so that it throws the responseHeader getter into the $promise then() callback function?
My service "Object" for reference:
myServices.factory('Object', ['$resource',
function($resource){
return $resource('object/:id', {id: '#id'}, {
update: {method: 'PUT'},
});
}
]);
I had the exact same problem. I used an interceptor in the resource definition to inject the http headers in the resource.
$resource('/api/resource/:id', {
id: '#id'
}, {
index: {
method: 'GET',
isArray: true,
interceptor: {
response: function(response) {
response.resource.$httpHeaders = response.headers;
return response.resource;
}
}
}});
Then, in the then callback, the http headers are accesible through $httpHeaders:
promise.then(function(resource) {
resource.$httpHeaders('header-name');
});
I think I had a similar problem: After POSTing a new resource I needed to get the Location header of the response, since the Id of the new resource was set on the server and then returned via this header.
I solved this problem by introducing my own promise like this:
app.factory('Rating', ['$resource',
function ($resource) {
// Use the $resource service to declare a restful client -- restangular might be a better alternative
var Rating = $resource('http://localhost:8080/courserater/rest/ratings-cors/:id', {id: '#id'}, {
'update': { method: 'PUT'}
});
return Rating;
}]);
function RestController($scope, $q, Rating) {
var rating = new Rating();
var defer = $q.defer(); // introduce a promise that will be resolved in the success callback
rating.$save(function(data, headers){ // perform a POST
// The response of the POST contains the url of the newly created resource
var newId = headers('Location').split('/').pop();
defer.resolve(newId)
});
return defer.promise;
})
.then (function(newId) {
// Load the newly created resource
return Rating.get({id: newId}).$promise; // perform GET
})
.then(function(rating){
// update the newly created resource
rating.score = 55;
return rating.$update(); // perform PUT
});
}
We can't use .then for returning the header because the promise doesn't allow for multiple return values. (e.g., (res, err))
This was a requested feature, and was closed https://github.com/angular/angular.js/issues/11056
... the then "callbacks" can have only [one] argument. The reason for this is that those "callbacks" correspond to the return value / exception from synchronous programming and you can't return multiple results / throw multiple exceptions from a regular function.

Resources