AngularJs $resource not invoking custom 'GET' - angularjs

I have created a simple RESTful service in .Net which is hosted here.
I am trying to invoke getByName action from my angularjs code. But, angularjs code is invoking default 'get' instead of 'getByName'
AngularJs code:
app.factory('UserResourceSvc',function($resource){
var baseApiUrl = "http://publicapitest.azurewebsites.net/";
//var baseApiUrl = "http://localhost:92/"
return $resource( baseApiUrl + 'api/Employee/:id',{id: "#id"},
{
getByName : {method: 'GET', params: {} , isArray: false}
}
);
});
I am invoking below function on button click to trigger API call.
$scope.getByName = function(){
UserResourceSvc.getByName(function(data){
debugger;
})
}
I am getting below error message :
angular.js:14794 Error: [$resource:badcfg] Error in resource configuration for action `getByName`. Expected response to contain an object but got an array (Request: GET http://publicapitest.azurewebsites.net/api/Employee)
http://errors.angularjs.org/1.6.7/$resource/badcfg?p0=getByName&p1=object&p2=array&p3=GET&p4=http%3A%2F%2Fpublicapitest.azurewebsites.net%2Fapi%2FEmployee
at angular.js:116
at $http.then.response.resource (angular-resource.js:757)
at processQueue (angular.js:17145)
at angular.js:17193
at Scope.$digest (angular.js:18331)
at Scope.$apply (angular.js:18628)
at done (angular.js:12619)
at completeRequest (angular.js:12863)
at XMLHttpRequest.requestLoaded (angular.js:12780) "Possibly unhandled rejection: {}"
When I checked in fiddler call is going to 'http://publicapitest.azurewebsites.net/api/Employee' instead of 'http://publicapitest.azurewebsites.net/api/Employee/getByName'
Am I missing anything?

You should specify method url as follows:
getByName : {method: 'GET', url: baseApiUrl + 'api/Employee/getByName', params: {} , isArray: false}

Related

AngularJS access $http on onNotification event PushNotification cordova plugin

I'm using the plugin https://github.com/phonegap-build/PushPlugin/ with Angular 1.3 and I need to send the regid to server when receive "registered" event.
The problem is that I don't have $http object to call my server on this context. How can I achieve that, please?
function onNotification(e){
if(e.event == "registered"){
var req = {
method: "POST",
url: "http://myurl.com/?var="+e.regid
};
$http(req).success(function(data){
alert(data);
});
}
}
I just learned how to inject $http into the event method:
$http = angular.injector(["ng"]).get("$http");
Change $http call as follows, .success is deprecated.
$http({
method: "POST",
url: "http://myurl.com/?var="+e.regid
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
alert(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Ref. : https://docs.angularjs.org/api/ng/service/$http
Regards.

How to access ajax response data outside ajax function in angularjs

I am fetching some data via http get ajax.
$.ajax({
type: "GET",
url: "/userdata/",
success: function(response){
$scope.steps = response.no_of_steps;
$scope.calories = response.calories;
},
error: function(){
alert("error");
}
});
If i print it on console from inside the success function, it prints the value like:
success: function(response){
var $scope.steps = response.no_of_steps;
var $scope.calories = response.calories;
console.log($scope.steps, $scope.calories);
},
But if i print it on colsole outside my ajax request, it print undefined. how is that so?
$.ajax({
...
});
console.log($scope.steps, $scope.calories);
this is continuation of my comment on your post above
you could do that by using $scope.$emit("custom-event-name"); of angular,
here you are actually watching $scope.steps and $scope.calories for change once your ajax call completes signify this by using $emit of angular
and then listen for that event by $scope.$on("custom-event-name", function(){})
and log it there, Please do make sure your "custom-event-name" is same in $emit and $on
in success callback : initialize the value and use $emit to emit an event named initialized as :-
$scope.steps = response.no_of_steps;
$scope.calories = response.calories;
$scope.$emit("initialized");
and then listen for that event initialized
$scope.$on('initialized', function () {
console.log($scope.steps + ' and ' + $scope.calories);
});
Couple of mistakes here.... use $http instead of $ajax, secondly you are defining your variables inside your success function so the scope is limited once it comes out of it... define your function globally in your controller and then access it inside your success function.
var $scope.steps => wrong way
$scope.steps = "something"; => right way.
You don't need to append var keyword with $scope in angularjs.
$scope.steps;
$scope.calories;
$.ajax({
type: "GET",
url: "/userdata/",
success: function(response){
$scope.steps = response.no_of_steps;
$scope.calories = response.calories;
},
error: function(){
alert("error");
}
});
Use $scope variables if you want to bind to the view and var does not and is local to the function it was declared in.
This works for me, i want to recommend you not to make use of $.ajax in angular js its a jquery function; i heard $http is faster than $.ajax function.
Hope this works for you if didnot work please inform me
//$scope.tablerows defined outside the function
$scope.tablerows;
module='user';
url=siteurl+"/admin/"+module+"/list";
BlockUi();
// $http is ajax call in angular js which is equivalent to $.ajax();
$http({
url : url,
method : "GET",
data : "",
headers : { 'Content-Type':undefined,
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
}
//responseText is the output of success call
}).then(function(responseText){
// assigning the response text on the variable
$scope.totaltablerows=responseText.data.response_data;
$scope.tablerows=$scope.totaltablerows;
UnblockUi();
},function(error){
//alert(JSON.stringify(error));
UnblockUi();
UnknownError(JSON.stringify(error));
});

Uncaught TypeError: Cannot read property 'parentNode' of null

Here is my code:
drop: function (node, data, dropRec, dropPosition) {
Ext.Ajax.request({
url: 'ajax_trees.php',
params:{
id: data.records[0].get('Id'),
action: "changeParent",
newParentId: dropRec.data.Id
}
});
structureStore.reload();
}
After ajax request finishes I reload the store and get Uncaught TypeError: Cannot read property 'parentNode' of null and after that everything crashes. Anyone has idea how to fix this error?
you don't reload your store after ajax request. The ajax request is an asynchronous work so if you want someting to do after ajax response, use success callback. That is the example;
Ext.Ajax.request({
url: 'ajax_trees.php',
params:{
id: data.records[0].get('Id'),
action: "changeParent",
newParentId: dropRec.data.Id
}
success : function(response) {
structureStore.reload();
}

How to retrieve objects from rest url with multiple parameters using angular

How can i create a factory that can retrieve data from
/rest/company/:companyid/employee/:id
when i use this url in the factory I get an error: Unknown provider companyidProvider
Thank you,
Kyle
Service:
app.factory('EmployeeByCompany', function ($resource,companyid) {
return $resource('app/rest/company/:companyid/employee/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': { method: 'GET'}
});
});
I'm guessing the error is from having the companyid as a parameter with $resource. What is the right way for a service to call this url?
If you are learning or geting started, try Restangular https://github.com/mgonto/restangular

TypeError when using $resource in Angularjs

I've got a weird error in angularjs. I've used $resource module in angularjs to make rest requests by registering this service
$provide.service("CustomerService", ['$resource', function ($resource) {
return $resource('/com/caspco/customers/:url:id', {}, {
query: { method: 'GET', isArray: true, params: {id: '#id'}},
find: { method: 'POST', isArray: true ,params:{url:'search'}},
.......... other actions ..........
});
}]);
in the rest server side I have a search method with the above url of find action that returns a json array. when I what to call find action by this way in the controller :
service.$find().$promise.$then(function (res) {
console.log("resource is" + res);
}, function (error) {
console.log("error");
});
It raises
TypeError: (anonymous function) angular.js:2070
(anonymous function) angular.js:1516
k.$apply angular.js:2575
(anonymous function) angular.js:4323
o.event.dispatch jquery.js:3
r.handle
Methods on the service are not prefixed by the '$' character. Methods on resources returned from the service are prefixed by '$'. The 'then' method on the $promise property is also not prefixed by '$'.
I think if you clean up that syntax you will be on the right track.
See the angular docs.
First off your code to call the service should be:
service.find().$promise.then(function (res) {
console.log("resource is" + res);
}, function (error) {
console.log("error");
});
The next thing to check, is your response actually an array. I got caught out big time with this, I was calling a service to get a list of objects from the backend, but before returning them, the backend was wrapping them inside a Response object, so what angular received was not an array, it was an object with an array inside it.

Resources