In the service.js file I have created two factories. Please let me know how to combine these two factories to one. So that I can import only one factory in my controller.
.factory('DeliveryReport', function($resource, API_URL) {
return $resource(API_URL + 'security/:userId/:timestamp/listOfDeliveries', {
userId : '#userId',
timestamp : '#timestamp'
}, {
update: {
method: 'PUT'
}
});
})
.factory('GuestReport', function($resource, API_URL) {
return $resource(API_URL + 'security/:userId/:timestamp/listOfGuests', {
userId : '#userId',
timestamp : '#timestamp'
}, {
update: {
method: 'PUT'
}
});
})
Related
Below is my AirTableService.js
(function () {
"use strict";
var AirTableService = function ($http, $q) {
var AirTableMethods = {
getMyRounds: function(AirTable_secret){
var deferObject_myRounds;
var myRounds_promise = $http.get('https://api.airtable.com/v0/XXXXXXX/Rounds?view=Main%20View&maxRecords=10&callback=JSON_CALLBACK', {
headers : {
'Authorization' : AirTable_secret.apikey,
'Content-Type' : 'application/json'
}
});
deferObject_myRounds = deferObject_myRounds || $q.defer();
myRounds_promise.then(function(data){
deferObject_myRounds.resolve(data);
});
return deferObject_myRounds.promise;
}
};
return AirTableMethods;
};
AirTableService.$inject = ['$http', '$q'];
angular.module('appGolf')
.service('AirTableService', AirTableService);
}());
In there as you can see, using AirTable's api I am trying to GET data from my table. I'm passing the parameters view and maxRecords and it works.
Documentation states I can pass sort,
which I then changed to,
https://api.airtable.com/v0/XXXXXXX/Rounds?view=Main%20View&maxRecords=10&sort=[{field:'RoundID',direction:'desc'}]&callback=JSON_CALLBACK
and clearly that doesn't work and it it gives me this error,
I know this is because sort is a array of objects and I know how I am passing this is incorrect.
My question is, how do you do this in AngularJS?
Thank you in advance.
Found the answer here
As mentioned there, I needed to add,
paramSerializer: '$httpParamSerializerJQLike',
And if you are interested, my function now looks like,
var myRounds_promise = $http.get('https://api.airtable.com/v0/XXXXX/Rounds?callback=JSON_CALLBACK', {
params: {
view: 'Main View',
maxRecords: 10,
sort: [{"field": 'RoundID', "direction":'desc'}]
},
paramSerializer: '$httpParamSerializerJQLike',
headers : {
'Authorization' : AirTable_secret.apikey,
'Content-Type' : 'application/json'
}
});
Thanks everyone for their suggestions and helping me out.
Your service is very verbose and hard to read. I would write it like this:
var app = angular.module("myApp", [ /* dependencies */ ]);
app.factory("AirTableService", ["$http", function($http) {
return {
getMyRounds: function(AirTable_secret) {
return $http.get('path/to/API', {
//put your sorting JSON object here in params
params: { sort: [{field: "RoundID", direction: "desc"}] },
headers: {
'Authorization' : AirTable_secret.apikey,
'Content-Type' : 'application/json'
}
});
},
anotherMethod: function() {
//etc....
},
yetAnotherMethod: function() {
return $http.post(); //maybe POST something
}
};
}]);
Inject it to your controller and use:
AirTableService.getMyRounds(airtableSecret).then(successCallback).catch(errorCallback);
I am using $resource service for my crud operations now i want to get data on a condition like get appointments whose starting date is today. I am fetching all data by
vm.appointments = AppointmentsService.query();
and my service code is
(function () {
'use strict';
angular
.module('appointments')
.factory('AppointmentsService', AppointmentsService);
AppointmentsService.$inject = ['$resource'];
function AppointmentsService($resource) {
return $resource('api/appointments/:appointmentId', {
appointmentId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
})();
Now can i give condition in this code blockAppointmentsService.query({condition}); or change my service in node rest API.
If yes, then what will be my AppointmentsService.query call
For your different url path, you can create new method like below or you can pass startDate as a query string
Controller :
For Path Param
vm.appointments = AppointmentsService.searchByDate({date:'03/30/2016'});
For Query Param
vm.appointments = AppointmentsService.searchByDate({StartDate:'03/01/2016',EndDate:'03/30/2016'});
Service:
function AppointmentsService($resource) {
return $resource('api/appointments/:appointmentId', {
appointmentId: '#_id'
}, {
update: {
method: 'PUT'
},
// For Path Param
searchByDate :{
method : 'GET',
url : 'your url/:date'
},
// For Query Param
searchByDate :{
method : 'GET',
url : 'your url/:startDate/:endDate' ,
params : { startDate : '#StartDate', endDate : '#EndDate' }
}
});
}
Update your service code...
(function () {
'use strict';
angular
.module('appointments')
.factory('AppointmentsService', AppointmentsService);
AppointmentsService.$inject = ['$resource'];
function AppointmentsService($resource) {
var service = {
get: $resource('api/appointments/:appointmentId',{
appointmentId: '#_id'
},{
method:'GET'
}),
update: $resource('api/appointments/:appointmentId',{
appointmentId: '#_id'
},{
method:'PUT'
}),
query:$resource('api/appointments',{
method:'GET',
isArray:true
})
queryByStartDate:$resource('api/appointments/:startDate',{
startDate: '#_startDate'
},{
method:'GET',
isArray:true
})
}
return service;
}
})();
And call queryByStartDate inside controller
var startDate = new Date(); //you can use $filter to format date
$scope.appointments = AppointmentsService.queryByStartDate({startDate:startDate});
I create a simple single page application with angularJS and laravel , , the method get, delete and store created , now how create the update method in my code?
I use below link in my app
https://scotch.io/tutorials/create-a-laravel-and-angular-single-page-comment-application
var app = angular.module('app',['ui.bootstrap'],function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
app.factory('Depot', function($http) {
return {
get : function() {
return $http.get('depots/depot');
},
save : function(commentData) {
return $http({
method: 'POST',
url: 'depots/depot',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(commentData)
});
},
destroy : function(depot_number) {
return $http.delete('depots/depot/' + depot_number);
}
}
});
app.controller('appCtrl', function($scope, $http, Depot) {
$scope.commentData = {};
$('#show_success').hide();
$('#show_remove').hide();
Depot.get()
.success(function(data) {
$scope.comments = data;
});
$scope.submitComment = function() {
Depot.save($scope.commentData)
.success(function(data) {
Depot.get()
.success(function(getData) {
$('#add_depot').hide();
$('#depot_name').val('');
$('#have_id').removeAttr('checked');
$('#show_success').show();
setTimeout(function() {
$('#show_success').hide();
},1500);
$scope.comments = getData;
});
})
.error(function(data) {
console.log(data);
});
};
$scope.deleteComment = function(id) {
Depot.destroy(id)
.success(function(data) {
Depot.get()
.success(function(getData) {
$('#show_remove').show();
setTimeout(function() {
$('#show_remove').hide();
},1500);
$scope.comments = getData;
});
});
};
});
You should read up on the documentation for ngResource. This is by far your best bet for a RESTful application.
I have answered another question a bit more detailed, perhaps it could help you too?
We really do need your endpoints / server-code to help you more.
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'
});
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.