Not able to retrieve the response from the angular js service - javascript

I wrote a angular js service which returns the response. But when I tried to call the service from the controller I am not able to get the exact response.
app.service('testservice', function($http){
var details= {};
details.getResponse = function() {
return $http({
url: 'send/getdata',
method: 'GET'
}).success(function(data, status, headers, config) {
this.getdata = data;
return getdata;
});
};
return details;
});
I am using the below controller to call the method.
app.controller('testcontroller',[ '$scope', '$http','testService',function($scope, $http,testService) {
var targetresponse = testService.getResponse();
alert(JSON.stringify(targetresponse))
})]);
I am getting the below response,
{"$$state":{"status":0,"pending":[[{"promise":{"$$state":{"status":0}}},null,null,null]]}}
Kindly, let me know the error here.

Your testservice service getResponse method should return a promise, and you can continue that promise chain inside your controller.
Service
details.getResponse = function() {
return $http({
url: 'send/getdata',
method: 'GET'
}).then(function(res) {
this.getdata = res.data;
return res.data;
});
};
You can use resolve that promise and get access of data inside .then function
var targetresponse = testService.getResponse();
targetresponse.then(function(data){
alert(JSON.stringify(data))
})

Srv.getData().then(function (success) {
var data = success.data;
$scope.myData = data;
}, function (error) {
});
Best way to to this.

Related

AngularJS factory returning State object instead of JSON data from promise

I have made two factory and calling first from second one, consuming second one factory in controller but instead of getting data as JSON, I'm getting data as $$State.
I'm new to angularJS tried many ways but not able to solve, please help.
app.factory('userDetails', ['APIService', '$q', function (APIService, $q) {
getDetails: function () {
var deferred = $q.defer();
var getFunc = function () {
APIService.doGetCall('Masters/employee/username/tarun')
.then(
function (data)
{
deferred.resolve(data);
},
function (data, status, headers, config)
{
deferred.reject('There was an error creating object'); })
return deferred.promise;
}
var a = getFunc();
return a;
}
}
vm.user = userDetails.getDetails();
console.log("user",vm.user);
response is as per below snippet
Response
You should be using .then function to get response there. Rather I'd say you don't need to create extra promise, its an anti-pattern. Where you could utilize the promise return by doGetCall method directly.
app.factory('userDetails', ['APIService', '$q', function(APIService, $q) {
getDetails: function() {
var getFunc = function() {
return APIService.doGetCall('Masters/employee/username/tarun');
}
var a = getFunc();
return a;
}
}]);
vm.user = userDetails.getDetails().then(function(response){
console.log(response.data);
vm.user = response.data;
console.log("user", vm.user);
}, function(error){
console.log(error)
}).catch(exceptionHandler);
userDetails.getDetails() returns a promise, Hence you need to use .then(onsuccess, onRejected)
userDetails.getDetails().then(function(data){
vm.user = data;
console.log("user",vm.user);
});
You've got the
return deferred.promise;
line inside the APIService.doGetCall function. It should be outside of it.

Angular Http put method giving error while passing data (server expecting form param )

I am trying to use the http put method to pass some data on server and server is looking for form param in put method.
var deferred = $q.defer();
$http({
method: 'PUT',
url: 'http.hello.com/rest/sample/'+fileName,
data: {status: status}
}).success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject(data);
});
return deferred.promise;
but server still giving missing data custom error then how can I pass the data in put method.
also try $.param() but it convert the data into string that's not correct
First of all $http itself returns a promise, so you do not need to $q
To pass the data in a neater way you can use the following
'use strict';
(function() {
function AppService($http) {
var AppService = {
putStatus(status, filename) {
return $http.put('http.hello.com/rest/sample/'+filename, {status: status})
}
};
return AppService;
}
angular.module('app')
.factory('AppService', AppService);
})();
Use as follows (somewhere in the controller)
AppService.putStatus(status, filename)
.then((response) => {
// do something on success
})
.catch((err) => {
//if error occured
});

How to get response from service on controller

I'm trying to separate the $http.post() call into a ".factory()", But would like to fetch the response which is coming async on the controller. Is there a way of doing that?
Controller:
Login.post($scope.user);
Factory:
.factory( 'Login' , function($http,SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function(user){
$http.post(serverUrl+'/login', user).
then(function(response) {
console.log(response);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
})
There is a .then() but I want that on the controller, so I can behave accordingly. Thank you!
Basically you need to return the $http.post promise, and from success function you could return a data that will return to the consumer of this method. So that you could easily call the factory method from controller & inside .then function of that call you could have success and error function.
Code
.factory('Login', function($http, SERVERURL) {
var serverUrl = SERVERURL;
return {
'post': function(user) {
return $http.post(serverUrl + '/login', user).
then(function(response) {
console.log(response);
return response.data; //return data from here
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
})
Controller
Login.post().then(function(data){ //success function
console.log(data)
}, function(error){ //error function
console.log(error);
})
You could add a callback param.
.factory( 'Login' , function($http,SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function(user, callback){
$http.post(serverUrl+'/login', user).
then(function(response) {
console.log(response);
callback(null, response);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
callback(response);
});
}
};
})
And your controller will become:
Login.post($scope.user, function(err, response) {
if(err) {} //do something if there is an error
// or deal with the response
});
To return any response to controller just do:
return {
'post' : function(user){
return $http.post(serverUrl+'/login', user);
}
};
In your controller you will already call.then()
Angular's $http methods return a Promise.
The $http API is based on the deferred/promise APIs exposed by the $q service.
Factory
Your method post is not yet returning anything but can quite simply return the Promise which is created by calling $http.post:
.factory('Login' , function($http, SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function (user) {
return $http.post(serverUrl + '/login', user)
// ^^^^^^
.then(function (response) {
console.log(response);
return response.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
});
Controller
Then consume the result of the returned Promise by calling then on it:
Login.post($scope.user).then(function (res) {
// do something with `res`...
});

AngularJS callback, copy the behavior of $http. Turn cache into promise

I want to create a cache for my http requests, so I want to duplicate the $http callbacks.
this is my function:
function getData() {
if(cacheExists()) {
return cache;
}
return $http({
method: 'POST',
url: 'http://something.com',
params: {something}
});
}
and this is how I handle it:
getData()
.success(function(data) {
$scope.spot = data.data;
console.log($scope.spot);
}).error(function(data) {
console.log('error');
});
this will work perfectly with angularjs $http method,
but will not work with my "cache", becuase the "cache" should have those callbacks: success & error, how do I create them?
Its because the $http returns a promise. You can solve this by using the $q service and return the cache as a promise.
//inject $q
function getData() {
var deffered = $q.defer()
if(cacheExists()) {
deffered.resolve(cache);
} else {
$http({
method: 'POST',
url: 'http://something.com',
params: {something}
})
.success(function(data) {
deffered.resolve(data);
})
.error(function(response) {
deffered.reject(response);
})
}
return deffered.promise;
}
So what's happening here that you are creating "deffered" as a promise. A Promise is basically a way to handle async tasks. And when you get a promise you need to resolve it, as you did with your return value from the http call. But with a $q deffered you are using 'then' instead of 'success'. Consider the code snippet below:
getData()
.then(function(data) {
$scope.spot = data.data;
console.log($scope.spot);
})
Hope this helps.
UPDATE
As of you example by handling errors you could do this:
getData()
.then(function(data) {
if(data.data) {
$scope.spot = data.data;
console.log($scope.spot);
} else {
console.log("its an err");
}
});
Or this
getData()
.then(successCallback, errorCallback);
function successCallback(data) {
$scope.spot = data.data;
console.log($scope.spot);
}
function errorCallback() {
console.log("its an err");
}

angularjs and $http request

Hello I'm new to AngularJs and trying to get json Data from my server. When the service gets executed, I see a clear response in Fiddler. But the success or the error function does not get executed, and so the service returns an empty array.
var app = angular.module('imageApp', []);
app.service('imageService', function ($http) {
var imageModels = [];
this.Images = function (url) {
$http({ method: 'GET', url: url }).success(function (data) {
imageModels = data;
}).error(function (data) {
imageModels = data || "Request failed";
});
return imageModels;
};
};
});
app.controller('ImageController', function (imageService, $scope) {
$scope.fetch = function (url) {
$scope.url = url;
$scope.ImageModels = imageService.Images($scope.url);
};
});
$http returns results asynchronously. So, return imageModels will execute before the success() or error() callbacks have had a chance to run. You need to wait for the promise that $http creates to resolve -- use then() in your controller.
Rather than repeat it here, see the solution from #Pete BD: https://stackoverflow.com/a/12513509/215945
Update your service like this.
app.service('imageService', function ($http, $q) {
this.Images = function (url) {
return $http({ method: 'GET', url: url }).success(function (data) {
$q.resolve(data);
}).error(function (data) {
$q.reject(data || "Request failed");
});
};
});
Then your controller, you can now wait for a promise to be returned from the service.
imageService.Images($scope.url)
.then(function(response){
// success
}).catch(function(error){
// error
})
So what happened? On your service, notice that we added $q to create a promise so we can reslove and reject the response from $http and make it "thenable" on the controller.
Writing a service to handle $http request is always a hassle for me, so I created this angular module to handle things for me. If you want you can check it out.

Categories

Resources