AngularJS Factory Parameter - angularjs

I'm trying to send a parameter to an angularjs service. Here is my service code :
angular.module('skyBiometryServices', ['ngResource'])
.factory('Facedetect', function( $resource ) {
return $resource('skyBiometry/facedetect', {}, {
query: {
method : 'GET',
params : {imageUrl: "http://cdn1-public.ladmedia.fr/var/public/storage/images/dossiers/presidentielles-2012/les-news-sur-les-presidentielles-2012/exclu-public-cauet-pour-ces-presidentielles-personne-ne-me-fait-rever-209063/2064021-1-fre-FR/Exclu-Public-Cauet-Pour-ces-presidentielles-personne-ne-me-fait-rever-!_portrait_w674.jpg"},
isArray: false
}
})
});
In my controller i have this :
function IndexCtrl($scope,Facedetect) {
$scope.text = Facedetect.query();
}
How can i send the imageurl into my services from the controller ? Something like this
function IndexCtrl($scope,Facedetect) {
$scope.text = Facedetect.query('MY IMAGE URL');
}
In advance thanks.

You can write your factory like this
app.factory('Facedetect',function($resource) {
return {
query: function(image_url) {
return $resource('skyBiometry/facedetect', {}, {
query: { method: 'GET', params: {imageUrl:image_url}, isArray: false }
}).query();
}
}
});
Now in your controller you can write
function IndexCtrl($scope, Facedetect) {
$scope.text = Facedetect.query("YOUR/IMAGE/URL");
}

If i understand correctly, you want something like that:
app.factory('myFactory',function(){
return{
prop: '',
setProp: function(newProp){
this.prop = newprop;
}
}
});
You should watch this:
https://egghead.io/lessons/angularjs-providers
And read this:
AngularJS: Service vs provider vs factory

With more research i found a solution :
factory('Facedetect', function( $resource ) {
return $resource('skyBiometry/facedetect', {}, {
query: {
method : 'GET',
params : {imageUrl: "http://cdn1-public.ladmedia.fr/var/public/storage/images/dossiers/presidentielles-2012/les-news-sur-les-presidentielles-2012/exclu-public-cauet-pour-ces-presidentielles-personne-ne-me-fait-rever-209063/2064021-1-fre-FR/Exclu-Public-Cauet-Pour-ces-presidentielles-personne-ne-me-fait-rever-!_portrait_w674.jpg"},
isArray: false
}
})
});
function IndexCtrl( $scope, $routeParams, Facedetect ) {
$scope.imageurl = 'http://flepi.net/images/personne-tendue.jpg';
$scope.text = $scope.text = Facedetect.get({imageUrl: $scope.imageurl});
}
I don't know if it's the best way but it works.

Related

$cancelRequest is not a function

I'm using angularjs 1.5.8.
I get this error when I'm trying to cancel an http request with angular :
$cancelRequest is not a function
My code :
app.factory('User', function($resource) {
var getUsersResource = $resource(
'/users',
null,
{get : {method: 'GET', isArray: true, cancellable: true}}
);
return {
getUsers : function() {
return getUsersResource.get({},
function(data) {
...
}, function(error) {
...
}
);
}
};
});
app.controller('InitController', function($rootScope, User, ...) {
...
User.getUsers();
...
}
app.factory('AuthInterceptor', function($q, $location, $injector) {
return {
responseError: function(response) {
if (response.status === 401) {
$injector.get('$http').pendingRequests.forEach(
function (pendingReq) {
pendingReq.$cancelRequest();
}
);
$location.path('login');
}
return $q.reject(response);
}
};
});
Do you know how I can solve this error ?
Thanks
The documentation suggests that $cancelRequest should be used with the resource object. From my initial review, it appears that you're correctly using $resource within the User factory. But, I'm not sure about how you're implementing this within the AuthInterceptor factory. It doesn't look like you're using User.getUsersSources() at all. Therefore, I believe the reason that you're getting that error is because you're not using $cancelRequestion correctly. That being said, you might have forgotten to include other parts of the code.
Ideally, the resolved $resource object from User.getUserResources() should be passed into AuthInteceptor.
I think that you should declare your service like that:
.factory('categoryService', ['$resource', function($resource) {
return $resource('/', {},
{
'get': {
'method': 'GET',
'cancellable': true,
'url': '/service/categories/get_by_store.json',
},
});
}])
And when you use this service, it should be called so:
if ( $scope.requestCategories ) {
$scope.requestCategories.$cancelRequest();
}
$scope.requestCategories = categoryService['get']({
}, function(res){
//some here
}, function(err){
//some here
});

Replace a lambda expression as IE is not accepting them

I am currently using a lambda expression on my data calls and it works great on Chrome. I have to make it work on IE as well and IE will not accept them. The code I am using is:
myApp.factory('User', ['$resource',
function saveDateFactory($resource) {
var myData = '';
//this grabs the data we need for the url below
function getMyData(data) {
myData = data;
}
//this is where we actually capture the data
return {
getMyData: getMyData,
resource: () => $resource(myData, {}, {
query: {
method: "GET", params: {}, isArray: true,
interceptor: {
response: function (response) {
//this is the piece we actually need
return response.data;
}
}
}
})
};
}]);
Does anyone have a suggestion on how I can change this so IE will accept it and it still works? Thanks for your help!
You can check the IE compatibility for ES6 here. This () => feature is called ExpressionBodies and it's not available for IE....
I suggest you to not use this ES6 features without an interpreter like BabelJs
myApp.factory('User', ['$resource',
function saveDateFactory($resource) {
var myData = '';
//this grabs the data we need for the url below
function getMyData(data) {
myData = data;
}
//this is where we actually capture the data
return {
getMyData: getMyData,
resource: function(){
$resource(myData, {}, {
query: {
method: "GET", params: {}, isArray: true,
interceptor: {
response: function (response) {
//this is the piece we actually need
return response.data;
}
}
}
});
}
};
}]);

Setting a factory variable in controller in angularjs

I need to set a factory variable in my controller. This variable is used for the url for returning a save function in my factory. I actually build this url as several pieces but this is a simplified version.
myApp.factory('SaveDate', ['$resource',
function saveDateFactory($resource, $http) {
var myData = '';
return $resource(myData, {}, {
query: { method: "POST", params: {}, isArray: false },
});
}]);
The function from my controller looks like this:
vm.myFunction1 = function ($resource) {
vm.myDate = '/test/MyProduct/SetSalesDate/988093099/108/2016/05/21';
SaveDate.myData = vm.myDate;
//this should save the date for milestones
SaveDate.query();
vm.cleanUp();
};
I have tried using an object instead of a primitive but it also didn't work. I have tested and my value for SaveDate.myData is being set accurately. If I hard code a value in the spot where I declare my variable in the factory, it will save perfectly. I am just not able to pass the variable successfully from my controller to my factory. I have tried a wide variety of ways to do this including using $watch. Thanks for your help on this!
When I added a function like this:
myApp.factory('SaveDate', ['$resource',
function saveDateFactory($resource, $http) {
var myData = {};
myData.getMyUrl = function (urlStuff) {
alert("in SaveDate" + urlStuff);
return $http.get(urlStuff);
}
return $resource(myData.getMyUrl, {}, {
query: { method: "POST", params: {}, isArray: false }
Adding this function throws the following error: Unknown provider: myDataProvider <- myData <- UserListController
You'll need to create a function in your factory as Clint said in the comments.
myApp.factory('SaveDate', ['$resource',
function saveDateFactory($resource, $http) {
var myData = '';
function setMyData(data) {
myData = data;
}
return {
setMyData: setMyData,
resource: $resource(myData, {}, {
query: { method: "POST", params: {}, isArray: false },
})
};
}]);
In your controller:
SaveDate.setMyData(vm.myDate);

Angular factory routeParam variable not changing

angular.module('app')
.factory('Answers', function ($resource, $routeParams, $location) {
return $resource('api/answers?questionid=' + $routeParams.questionId, {
answerId: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
$scope.findAnswers = function() {
Answers.query(function(answers) {
$scope.answers = answers;
});
};
It seems like the $routeParams variable isn't being updated as I navigate around my app through different routes. Is this the case w/ services? I'm guessing I should define the variable in my controller and then pass it into my service?
EDIT:
angular.module('intquestApp')
.factory('Answers', function ($resource, $routeParams, $location) {
return {
get: function(questionId) {
return $resource('api/answers?questionid=' + questionId, {
update: {
method: 'PUT'
}
});
}
};
});
Answers.get($routeParams.questionId, function(answers) {
console.log(answers);
$scope.answers = answers;
});
I believe the approach is to inject $routeParams into your Controller instead and pass the value to the service.
See here: Use $routeParams in service
so inside your Controller:
Answers.get(passRouteParamValueHere, function(answers) {
$scope.answers = answers;
});
EDIT
Why do you have update within get? Here's something you could try but haven't tested it:
.factory('Answers',['$resource', function ($resource) {
return $resource('/api/answers/?questionid=' + questionId, {}, {
get: { method: 'GET'}
});
}])
but I prefer this approach:
.factory('Answers',['$resource', function ($resource) {
return $resource('/api/answers/:qid', {}, {
get: { method: 'GET'}
});
}])
and then:
Answers.get({qid: questionIDFromRouteParam}, function(answers) {
$scope.answers = answers;
});
Just a little cleaner

how to make Generic method for rest call in angularjs

how to make Generic method for rest call in angularjs ?
i have tried for single request, it's working fine
UIAppRoute.controller('test', ['$scope', 'checkStatus', function($scope, checkStatus) {
$scope.data = {};
checkStatus.query(function(response) {
$scope.data.resp = response;
});
}])
UIAppResource.factory('checkStatus', function($resource){
return $resource(baseURL + 'status', {}, {'query': {method: 'GET', isArray: false}})
})
I want to make this as generic for all the request
Please share any sample,.. thanks in advance
I'm using something like this :
.factory('factoryResource', ['$resource', 'CONF',
function($resource, CONF) {
return {
get: function(endPoint, method) {
var resource = $resource(CONF.baseUrl + endPoint, {}, {
get: {
method: method || 'GET'
}
});
return resource.get().$promise;
}
};
}
])
called by :
factoryResource.get(CONF.testEndPoint, "POST"); // make a POST and return a promise and a data object
factoryResource.get(CONF.testEndPoint, "GET"); // make a GETand return a promise and a data object
factoryResource.get(CONF.testEndPoint); // make a GETand return a promise and a data object
with a config file having :
angular.module('app.constant', [])
.constant('CONF', {
baseUrl: 'http://localhost:8787',
testEndPoint: '/api/test'
});

Resources