AngularJS $resource success and error callback - javascript

I have a simple code here that works however I wanted to display the success and error callbacks. This is my code:
angular
.module('studentInfoApp')
.factory('Student', Student)
.controller('StudentsController', StudentsController)
.config(config);
function config($routeProvider) {
$routeProvider
.when('/', {
controller: 'StudentsController',
templateUrl: 'app/views/student-list.html'
})
}
function Student($resource) {
return $resource('/students');
}
function StudentsController(Student, $scope, $http) {
Student.query(function(data) {
$scope.students = data;
});
}
As you can see the function Student() just returns the resource but I can't get the success and error callback if I use the .then for example. Am I missing something here? Thank you!

Here is a solution:
Student.query(function(data, headers) {
// OK
$scope.students = data;
}, function(response) {
// KO
});
Another one using the promise directly:
Student.query().$promise.then(function(response) {
// OK
$scope.students = response.data;
}, function(response) {
// KO
});

When using angular $resources you can just save the query directly to your variable. It will then hold the promise and when data returns the data itself.
If you need to handle success/error you can just use the saved promise and add success and error callbacks like below.
$scope.students = Student.query();
$scope.students.$promise.then( function(response) {
console.log('success');
}, function (error) {
console.log('error');
});

Managed to get it working, but if there are better ways to do it please feel free to post it also. This is my code now:
function StudentsController(Student, $scope) {
Student.query(function(data) {
$scope.students = data;
})
.$promise.then(function successCallback(response) {
console.log('success');
}, function errorCallback(error) {
console.log('error');
});
}

Related

Angular fetch value using service getting error success is not a function

service.js
angular.module('users.background.image', [])
.factory('changebgimage', ['$http', '$q', '$rootScope', function($http, $q, $rootScope){
'use strict';
var service = {
changeRandomImage : changeRandomImage
};
function changeRandomImage(){
/*var random = $scope.data[Math.floor(Math.random() * $scope.data.length)];
$scope.imageSource = random;*/
var url = 'webService/imageUrl.htm';
var deferred = $q.defer();
$http.get(url)
.success(function(data){
deferred.resolve(data.data);
})
.error(function(error){
deferred.reject(error.message);
});
return deferred.promise;
}
return service;
}]);
aa.js
angular.module('users.da', ['users.background.image'])
.controller('da', ['user', '$scope', 'changebgimage', function (user, $scope, changebgimage) {
'use strict';
changebgimage.changeRandomImage()
.success(function (data) {
console.log(data);
}).error(function(error){
console.log(error);
});
}]);
imageUrl.htm
[{
"id": 1,
"path": "images/bg/1.jpg"
},
{
"id": 2,
"path": "images/bg/2.jpg"
},
{
"id": 3,
"path": "images/bg/3.jpg"
},
{
"id": 4,
"path": "images/bg/4.jpg"
},
{
"id": 5,
"path": "images/bg/5.jpg"
},
{
"id": 6,
"path": "images/bg/6.jpg"
}]
I am trying to get the value from service in angular but getting error changebgimage.changeRandomImage(...).success is not a function
I can't understand why i am getting this error. Can anyone please take a look and assist me what is doing wrong on it promise is passing correctly.
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise. Follow $http Service Documentation
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
A promise object doesn't have success() or error() methods, it has then() and catch() (and also finally()) methods
.success() method is deprecated, use .then().
Like:
$http.get(url).then(function (data) {
// handle response data
}, function (error) {
// handle error from api
}).catch(function (err) {
// handle error from response.
});
Looks like they removed that function in new version.
Try to use promises with "then"
$http.get(url).then(function(response) {
// data is under response.data
});
There is an article on this:
http://www.codelord.net/2015/05/25/dont-use-%24https-success/
Removed deferred.resolve(data.data);
because data.data has no value data has the value
function changeRandomImage(){
var url = 'webService/imageUrl.htm';
var deferred = $q.defer();
$http.get(url)
.success(function(data){
deferred.resolve(data);
})
.error(function(error){
deferred.reject(error.message);
});
return deferred.promise;
}

AngularJS - Unable to call http serrvice using factory

To resolve my issue I have gone through many articles on different sites, but none resolved it.
I'm writing a simple AngularJS application. I'm quite new to Angular. I have written a factory method which call the $http service which gets the data from the web api. Web api is running fine and its returning the JSON object as expected.
Angular Code
var app = angular.module("app", [])
.controller("controller", function ($scope, WebFactory) {
$scope.data = "data";
$scope.error = "error";
$scope.data=WebFactory.getData();
})
.factory("WebFactory", function ($http) {
var obj = {};
obj.getData = function()
{
$http({
method: "GET",
url: "http://localhost:37103/api/employee",
}).then(function success(response) {
return response.data;
})
.then(function error(response) {
return response;
});
return 'No data';
}
return obj;
});
HTML code
<body ng-controller="controller">
data: {{data}}
<br/>
error: {{error}}
<br />
I have spent 2 days, but still dont know why its not working.
Try something like this instead:
var app = angular.module("app", [])
.controller("controller", function ($scope, WebFactory) {
$scope.data = "data";
$scope.error = "error";
$scope.data = {}
WebFactory.getData().then(function success(response) {
$scope.data = response.data;
});
})
.factory("WebFactory", function ($http) {
var obj = {};
obj.getData = function()
{
return $http({
method: "GET",
url: "http://localhost:37103/api/employee",
})
}
return obj;
});
First of all, you're missing an ng-app declaration
Secondly, you are misusing the then callback. It accepts three parameters: success callback, error callback, finally callback.
As the first then executes the success, then it executes the second callback that always returns the response, but I assume it is not intended to be that way and you could use the get function which is more easy to use.
It should be:
$http.get("http://localhost:37103/api/employee").then(function(response){
//Do something with successfull response
},
function(error){ //do something with the error});
See documentation about promises
Lastly, you are dealing with promises and async code, yet returning response or string instead of the promise with the result. So the getData() should look like this:
obj.getData = function(){
return $http.get("http://localhost:37103/api/employee");
}
And use the then(success,error,finally) callbacks in the controller or if you want to provide values on the error/finally callbacks in the service, you should use the $q service
obj.getData(){
var deferred = $q.defer();
$http.get(...).then(function(response){
deferred.resolve(response.data);
},
function(error){
deferred.reject("No Data");
});
return deferred.promise;
}
Of course you would have to provide $q service to the WebFactory

Getting data to $scope fails in angularjs

I'm trying to pass data to $scope.post by doing it this way, but it doesn't want to work like I imagine it to do. I get no errors in the console and the code is inside the PostController.
var PostController = function ($scope, $location, $routeParams, $http, Post, User) {
$scope.post = {};
$scope.getById = function (id) {
return $http.get('/api/Post/' + id).success(function (data) {
$scope.post = data;
});
}
$scope.getById($routeParams.id);
console.log($scope.post);
}
Here's the routing too:
when('/post/:id', { controller: PostController, templateUrl: 'post.html' }).
Edit, whole PostController added.
getById is an async call, it's not failing, you're just not waiting! Use .then to return a promise and do the assignment in the callback:
$scope.getById = function (id) {
return $http.get('/api/Post/' + id).then(function (result) {
return result.data
});
}
$scope.getById($routeParams.id).then(function(data) {
$scope.post = data;
});
console.log($scope.post); is called before callback, so there is no values.if you want to get the value in console, try this..
$scope.getById = function (id) {
return $http.get('/api/Post/' + id).success(function (data) {
$scope.post = data;
console.log($scope.post);
});
}
$http get returns promise.
That means, that function inside success, isn't invoked at once.
It's not intuitive, but that is how promises work.
To track resulting data, insert console.log inside success function
return $http.get('/api/Post/' + id).success(function (data) {
$scope.post = data;
console.log('$scope post: ',$scope.post);
});
You will see data returned from get call to debug ( you can also print this variable in your view ).
How it works:
$http.get returns a promise, and also adds addtional success and error function.
After $http.get, you chain promise to success function
$http.get('/api/Post/' + id).success
which is called after successful server response ( http codes from 200 to 299 ), and error function is called where there is failure ( 400 - 499 codes ).
The first two answers are probably the solution to your problem... since your console.log is executing before the callback to the HTTP request. However, it is good practice to also handle HTTP errors, which could always be a problem. Here is an example of how you would do that:
$http.get('/api/Post/' + id).
success(function(data, status, headers, config) {
//handle success
}).
error(function(data, status, headers, config) {
//handle error
});

Angular $http get works in browser but not on device - Ionic

I have a factory returning an object calling an internal resource containing JSON as so:
.factory('cardFactory', function ($q, $http) {
return {
getOtherStuff: function () {
var deferred = $q.defer(),
httpPromise = $http.get('/static/cards.json');
httpPromise.then(function (response) {
deferred.resolve(response);
}, function (error) {
console.error(error);
});
return deferred.promise;
}
};
});
In my controller I call it like this:
var cardSuccess = function(data, status, headers, config) {
$scope.cards = data.data;
};
cardFactory.getOtherStuff()
.then(cardSuccess, cardError);
In the browser $scope.cards in populated but on the device it doesn't populate.
Any ideas why?
Hmm.., not sure.
I have it in a different way in my Ionic app, working great.
.factory('cardFactory', function ( $http ) {
var promise;
var cards = {
getOtherStuff: function() {
if ( !promise ) {
// $http returns a promise, which has a then function, which also returns a promise
promise = $http.get( '/static/cards.json' ).then(function (response) {
// The then function here is an opportunity to modify the response
// The return value gets picked up by the then in the controller.
return response.data;
});
}
return promise; // Return the promise to the controller
}
};
return cards;
})
Then, on the controller, calling it by:
$scope.getData = function() {
// Call the async method and then do stuff with what is returned inside our own then function
cardFactory.getOtherStuff().then(function(d) {
$scope.cards= d;
});
}
$scope.getData();
Hope it helps.
[EDIT:] Could it be the $http.get url, being relative? Have you tried with an absolute url?
Replace $scope.cards=data.data with "$scope.cards=data"
var cardSuccess = function(data, status, headers, config) {
$scope.cards = data;
};
try removing the leading slash in your url for $http. Try using 'static/cards.json' instead of '/static/cards.json'
I actually had the same problem and this fixed it for me. Hope it helps!

unable to get data from $q into scope

I'm trying to bind some data being returned from an API to my scope using promises with $q, I am able to pull the data from the server without any issue (I can see JSON being returned using fiddler) however the $scope variable remains empty, any help would be greatly appreciated! Thanks in advance.
Code:
toDoListService.js
app.factory("toDoListService", function ($http, $q) {
var deferred = $q.defer();
return {
get: function () {
$http({ method: 'GET', url: '/api/todo/' }).
success(function (data) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
});
toDoListController.js
app.controller("toDoListController", function($scope, toDoListService){
$scope.toDoList = toDoListService.get();
});
First of all you should put var deferred = $q.defer(); in your get function, so that every get has it's own deferred object.
Second what get actually returns is a promise. So you need to access you data in this way:
app.controller("toDoListController", function($scope, toDoListService){
toDoListService.get().then(function(data){
$scope.toDoList = data;
});
});
Right now, your $scope.toDoList is bound to a promise. This means of binding used to work, but was deprecated in, I think, 1.2.
As Michael suggests, you must do:
app.controller("toDoListController", function($scope, toDoListService){
toDoListService.get().then(function(data){
$scope.toDoList = data;
});
});
Also, using $q is not required here at all, as $http returns a promise anyway. Therefore, you could just do:
app.factory("toDoListService", function ($http){
return {
get: function () {
return $http({ method: 'GET', url: '/api/todo/' });
}
};
});
You can simplify your code by using this:
toDoListService.js
app.factory("toDoListService", function ($http, $q) {
return {
get: function () {
return $http({ method: 'GET', url: '/api/todo/' });
}
}
});
toDoListController.js
app.controller("toDoListController", function($scope, toDoListService) {
toDoListService.get().then(function(response){
$scope.toDoList = response.data;
return response;
});
});
Be sure to return response in your success callback, otherwise chained promises would not receive it.

Categories

Resources