I defined the following service:
myServices.factory('MyManager', ['$resource',
function ($resource) {
return $resource('../rest/contract/:contractId', {contractId:'#contractId'}, {
findById: {method: 'GET', contractId: '#contractId'}
});
}]);
I want to make the REST call and, in my controller, I am doing this:
MyManager.findById(contractId,
// on success
function (response) {
// do
},
// on error
function () {
alert("Error");
});
However, the generated URL is <base>/rest/contract and no path variable is appended. The parameter I am passing to findById is not null.
What am I doing wrong?
You have to pass the parameter as an object:
MyManager.findById({contractId: contractId}, ...
Related
AngularJS : 1.4.X
Scenario 1: Works fine
Scenario 2: Throws 404 error on line xhr.send(isUndefined(post) ? null : post); in angular.js
I'm trying to add inbuilt angular cache to our existing app, As i mentioned in scenario 1 we consume rest call in factory 'restFactory' and inject the factory to controller 'bookController', the promise is resolved and data loads fine.
Factory: restFactory
(function () {
"use strict";
angular.module('myApp').factory("restFactory",['$http','confi', function($http,config){
function getBooks (){
return $http.get(config.serverName+"bookshelf/rest/books/data/geRestBooks");
}
return {
getBooks : getBooks
};
}]);
})();
Controller: bookController
$scope.getComicbooks = function() {
restFactory.getBooks().then(function(response) {
$scope.names = response.data;
}, function(error) {
$scope.error = error;
$scope.names = [];
});
};
Now in scenario 2, I changed the service call in factory to object with more details. But i get exception from controller while resolving the promise ( i have only added the changed code )
function getBooks (){
return $http.get({
cache: true,
method: 'GET',
url : config.serverName+"bookshelf/rest/books/data/geRestBooks"
});
}
ERROR: angular.js:10765 GET http://127.0.0.1:53814/views/[object%20Object] 404 (Not Found)
Network Tab:
In scenario#1 this would have been a method call getBooks
If you are going to specify the method, then you should just use the $http constructor method, not the get method.
Instead of
function getBooks (){
return $http.get({
cache: true,
method: 'GET',
url : config.serverName+"bookshelf/rest/books/data/geRestBooks"
});
}
Try
function getBooks (){
return $http({
cache: true,
method: 'GET',
url : config.serverName+"bookshelf/rest/books/data/geRestBooks"
});
}
I have an angular factory doing some $http communication to the server and returning a string. However I get the Cannot read property 'then' of undefined error. I read here and here with similar problems however I was not able to resolve my problem.
This is the service code:
factory("availabilityService", ['$http', function ($http) {
return {
checkAvailability1: function (element, string) {
// ..... some object creation code ......
$http({
method: 'POST',
url: 'server/server.php',
data: AvailableObj,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function successCallback(response) {
return response;
}, function errorCallback(response) {
});
}
}
}]);
Inside a controller:
$scope.checkAvailability = function (element, string) {
availabilityService.checkAvailability1(element, string).then(function (response) { //on this line the error occurs
console.log(response);
});
You need to return the promise returned by $http i.e add a 'return' in front of $http to get your code working like below :
return $http(...)
.then(function successCallback(response) {
return response;
}, function errorCallback(response) {
});
This is because, the function you have called from the controller should have a .then method on it i.e it should be a promise. checkAvailability1 in angular returns a promise which needs to be returned back by your function $http in the factory. You are just returning the response from the success callback which is not expected by your method in the controller.
here is a set up for me to call a php script to get data from an external API. What I did is to set up a factory like such:
app.factory('loadAPI', function ($http) {
var doRequest = function() {
return $http({
method: 'JSON',
url: 'api.php'
});
};
return {
dataReturn: function() { return doRequest(); }
};
});
And then inside my .controller I use the following script to process data:
loadAPI.dataReturn().success(function(data, status){
...
}
Now since the external API provides many interfaces, I like to pass parameter to the .factory so it can process multiple different type of interfaces (instead of creating multiple .factory to process them).
Here is my concept:
loadAPI.dataReturn(parameter).success(function(data, status){
...
}
app.factory('loadAPI', function ($http) {
var doRequest = function(parameter) {
return $http({
method: 'JSON',
url: 'api.php?p=' + parameter
});
};
return {
dataReturn: function(parameter) { return doRequest(parameter); }
};
});
It didn't work.
The concept would work. I tried it and it returns data correctly. There perhaps are easier ways to pass the parameter to $http. I suspect something wrong with your api.php not reading the parameter correctly.
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);
I have this resource:
myModule.factory('MyResource', ['$resource', 'geoLocationService', function ($resource, geoLocationService ) {
return $resource('/blabla', {}, {
'getData': { method: 'GET', params: { city: geoLocationService.getMyCity() } }
});
}]);
The problem is that by the time of calling MyResource.getData(), geoLocationService haven't done to fetch the location.
geoLocationService has a promise which will allow me call
geoLocationService.promise.then(...)
But I don't know how I can integrate this promise with the resource. Any idea?
EDIT
I am looking for something like:
myModule.factory('MyResource', ['$resource', 'geoLocationService', function ($resource, geoLocationService ) {
return $resource('/blabla', {}, {
'getData': { method: 'GET', beforeFetchPromise: geoLocationService.promise, { city: geoLocationService.getMyCity() } }
});
}]);
So only when geoLocationService.promise is resolved or rejected, the ajax call with parameters will occur.
I think you should add a promise in your controller:
$scope.resultsFromResource = YourResourceName.query().$promise.then(function(result){
// code inside promise
})
I would also suggest that you either use query as in my example or remove single quotes around your name getData if you want to keep that.