AngularJS Resource with relation between tables - javascript

is this possible with AngularJS Resource?
/api/client/:id/jobs (get all the jobs from this client)
/api/client/:id/job/:jobId (get the job form this client)
My Factory:
.factory('Client', ['$resource', 'Api',
function ($resource, Api) {
var Client = $resource(Api.url() + 'client/:id/',
{
id: '#id'
},
{
'update' : { method: 'PUT', isArray: false }
}
);
return Client;
}
]);
Thanks!

I found a solution for my problem.
I have to create another factory to do the job:
.factory('ClientJobs', ['$resource', 'Api',
function ($resource, Api) {
var ClientJobs = $resource(Api.url() + 'client/:clientId/job/:jobId',
{
clientId: '#Id',
jobId: '#Id'
},
{
'query': { method: 'GET', isArray: true },
'update': { method: 'PUT' }
}
);
return ClientJobs;
}
]);
And, i can use the factory like this:
ClientJobs.save({clientId:clientId, jobId:job.id}, job, function (result) {
deferred.resolve(result);
}, function (reason) {
deferred.reject(reason);
});
Now, everything is working.
And for help those people who are working with UI-ROUTER, there is this question with an excellent answer about complex states like mine and nested views:
Nested Views with Nested States

Related

Passing complex object from angular js factory to web api using $resource

I am passing an object to angular factory it is throwing error.
factory:
visitorApp.factory('loginRepository', function ($resource) {
return {
VerifyVisitor: $resource('/api/VisitorWeb/VerifyLogin', {}, {
query: { method: 'POST', params: {loginModel:loginModel}, isArray: true }
})
};
});
The complex object i am trying to pass is loginModel.
From controller call to factory.
visitorApp.controller('LoginController', function ($scope,$location,$route,loginRepository) {
$scope.submit = function (isValid) {
if (isValid) {
var loginModel = {
UserName: $scope.UserName,
PassWord: $scope.Password
};
var response = loginRepository.VerifyVisitor.query(loginModel);
alert(response);
}
}
});
Error: loginModel is not defined
Web Api Method which is being called.
[HttpPost]
public string VerifyLogin(UserLoginDomainModel loginModel)
{
var msg = _loginService.Login(loginModel);
return msg;
}
Is it the right way of using $resource to post a request and pass complex object.
Your service should look something like this:
visitorApp.factory('loginRepository', function ($resource) {
return {
VerifyVisitor: $resource('/api/VisitorWeb/VerifyLogin', {},
{
query: {
method: 'POST',
params: {loginModel: '#loginModel'},
isArray: true }
})
};
});
The parameter variables are enclosed in quotes and prefixed with an #.

Problems when passing parameters of an Angular application for a Rails controller

I have an application made in angularjs, but I'm having trouble reading the parameters on the server side.
As I'm sending the data:
api.factory('AuthProvider', function($resource, ENV){
var baseUrl = ENV.apiEndpoint;
return $resource(baseUrl, null,
{
login: {
method: 'POST',
url: baseUrl+'sessions'
}
});
});
angular.module('tuneduc.controllers.admin',[])
.controller('AdminController', function($scope, $location, AuthProvider) {
var auth;
$scope.login = function (credentials) {
auth = new AuthProvider(credentials)
auth.$login(function(res) {
console.log('success');
},
function(res) {
console.log(res.data.errors);
})
}
});
So the parameters are coming this way on the server:
{"{\"email\":\"assdaf#adfasdf.com\",\"password\":\"sadfsdf\"}"=>nil, "controller"=>"sessions", "action"=>"create"}
I've tried using JSON.stringify () but failed.

Angular Resource not sending request to API

I am writing a basic CRUD Angular app of sorts and have been using $resource throughout. The issue is that when I am trying to issue a get request to an API endpoint I am getting an error in resource:
[Log] Object (job-detail.js, line 30)
config: Object
headers: Object
method: "GET"
transformRequest: Array[1]
transformResponse: Array[1]
url: "http://127.0.0.1:8000/estimators/1"
__proto__: Object
data: null
headers: function (name) {
get arguments: function () {
get caller: function () {
length: 1
name: ""
prototype: Object
set arguments: function () {
set caller: function () {
__proto__: function () {
status: 0
statusText: ""
__proto__: Object
I have no idea what is going wrong because I have tested that URL and it works fine. Also, I have used $resource in the exact same fashion, just on a different endpoint and it is working fine. Lastly, $resource isn't even sending the request, on my API it's not logging any requests to the endpoint. I am at a loss, here is the relevant code:
angular.module('lincorFeApp.controllers')
.controller('JobDetailCtrl', ['$scope', '$routeParams', 'Estimator', '$location',
function($scope, $routeParams, Estimator, $location) {
getEstimator();
function getEstimator() {
$scope.estimator = Estimator.get({ pk : $scope.job.estimator }, function() {
console.log($scope.estimator.name);
}, function(response) {
console.log(response);
});
}
}
]);
and in services.js:
myApp.factory('Estimator', function($resource) {
return $resource('http://127.0.0.1:8000/estimators/:pk', { pk : '#pk' }, {
update : { method: 'PUT' },
delete : { method: 'DELETE' }
});
});
Any help would be greatly appreciated!

how to build angular $resource POST request to server?

I can't catch request on ASP.NET MVC project on server side controller from AngularJS:
var appDirective = angular.module('app.directive', []);
var xmplService = angular.module('app.service', ['ngResource']);
var appFilter = angular.module('app.filter', []);
var app = angular.module('app', ['app.service', 'app.directive', 'app.filter', 'solo.table']);
xmplService
.factory('testResource1', function ($resource) {
return $resource('/SoloAngularTable/TestMethod3', { id: '#id' }, { charge: { method: 'POST' } });
});
app
.controller('ContentPlaceHolder1Controller', function ($scope, $http, testResource1) {
testResource1.find({ id: 123 }, function (data) {
alert('success');
});
});
On MVC Controller I have a method that can't catch request:
[HttpPost]
public JsonResult TestMethod3(int id)
{
var data = new { User = "Alex" };
return Json(data);
}
How to build simple request to server side with AngularJS $resource and catch request?
find is not a default action for $resource. The defaults are:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
You will have to create/specify the find action. You are currently creating/specifying a charge action. Perhaps this is what you meant to use?
If you want to use find, here is the fix:
.factory('testResource1', function ($resource) {
return $resource('/SoloAngularTable/TestMethod3', { id: '#id' }, {
charge: { method: 'POST' },
find: { method: 'POST' } // Added `find` action
});
});
If you meant to use charge, here is the fix:
.controller('ContentPlaceHolder1Controller', function ($scope, $http, testResource1) {
testResource1.charge({ id: 123 }, function (data) {
alert('success');
});
});

AngularJS $resource & cache factory

I have implemented angular $resource with custom functions and parameters as follows:-
.factory('CandidateService', ['$resource', function ($resource) {
return $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "#id" } }
});
}]);
And I am consuming this in the controller as follows:-
.controller('Controller', ['CandidateService', function ($scope, CandidateService) {
$scope.candidateList = [];
CandidateService.getAll(function (data) {
$scope.candidateList = data;
});
}]);
This is working absolutely fine. Now I need to cache the data from the api into the CandidateService Factory so it is not loaded eveytime I move between the controllers.
So I thought i would do something as follows:-
.factory('CandidateService', ['$resource', function ($resource) {
var Api = $resource("api/:action/:id", {},
{
'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
'getCandidate': { method: 'GET', params: { action: "Candidate", id: "#id" } }
});
var candidateDataLoaded = false;
var candidateData = [];
return {
getCandidates: function () {
if (!candidateDataLoaded) {
Api.getAll(function (data) {
angular.copy(data, candidateData);
});
}
return candidateData;
}
}
}]);
But I just cant get this to work. I think it has something to do with angular factory being a singleton.
Is my approach correct to implement the caching?
You can use the $cacheFactory object.
See : http://docs.angularjs.org/api/ng.$cacheFactory
You can cache $http request like that :
var $httpDefaultCache = $cacheFactory.get('$http');
If you want to retrieve a specific url in cache do :
var cachedData = $httpDefaultCache.get('http://myserver.com/foo/bar/123');
$You can clear the cache too :
$httpDefaultCache.remove('http://myserver.com/foo/bar/123');
or :
$httpDefaultCache.removeAll();
Complete post here : Power up $http with caching

Categories

Resources