unable to get data from $q into scope - javascript

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.

Related

How does asynchronous call work in AngularJS 1.X? $Http call not returning value

I have the following function named getvalue. It is inside an AngularJS module together with a controller. I am trying to call this function on click event invoking another function in a controller.(I hope I am clear)
function:
function getvalue(Data, $http) {
var value=undefined;
$http({
url: /myurl,
method: "GET",
params: {
tmp: Data.tmp,
pressure: Data.pressure
}
}).success(function (data, status, headers, config) {
value=parseFloat( console.log(data));//console working here
return value;
});
return value;
}
Code inside Controller
value= getvalue(formData, $http );
alert(value);//undefined here. Seems like value is never changed.
I have not getting the value on alert but console is printing the value. I need help if possible for two issues.
How can I change the value from inside success and return to controller?
Is there any way that I don't have to inject $Http from controller to function?
-----It would be nice if I can do that for unit testing.
you would ideally want to pull the $http service out of the controller and make a factory to do those calls.
in the factory have a function that accepts the data you are wanting to send and have it return the promise back to the controller
something like this
Repo
app.factory("fooRepo", ["$http", function($http){
return {
getValue: function(data){
return $http({
method: "POST",
url: "/myUrl"
});
}
};
}]);
Serivce
app.factory("foo", ["$q", "fooRepo", function($q, fooRepo){
return {
getValue: function(data){
var deferred = $q.defer();
fooRepo.getValue(data)
.success(function(results){
//do some work
deferred.resolve(results);
})
.error(function(error){
// do some work
deferred.reject(error);
});
return deferred.promise;
}
}
}]);
here is the controller
app.controller("fooCtrl", ["foo", function(foo){
foo.getValue(dataHere)
.then(function(results){
// do something here
});
}]);
Added Plunkr
As you are calling a method which is doing async call, you must return promise from there as you don't know when data will get back from the ajax. On success of that ajax you should update your variable. Outside of ajax function you will get undefined value because value is returned in async manner.
Function
function getvalue(Data) {
var value=undefined;
return $http({
url: /myurl,
method: "GET",
params: {
tmp: Data.tmp,
pressure: Data.pressure
}
})
}
Controller
getvalue(formData).success(function (data, status, headers, config) {
console.log(data);//you will get data here
});
A $http-Request is async. That means that alert will be called before the .success(..) callback is executed.
You can see a result on the console because it reflects changes made after the call of console.log().
Calling alert(value); in the .success()-Callback will shield the desired result.
Replace:
}).success(function (data, status, headers, config) {
value=parseFloat( console.log(data));//console working here
return value;
});
with:
}).success(function (data, status, headers, config) {
alert(parseFloat(data));
});

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!

returning value to higher scope inside from a chained functions in angular js

I have a function getUsers that I want to return JSON from an web api .. but I cant seem to get the data out, I can't return the data because the function is inside $http. What should i do ?
function getUsers() {
$http({ method: 'GET', url: '/api/loginapi/userdetails' })
.success(function (data, status, headers, config) {
details = data;
});
return details;
}
$http makes an asynchronous call, so you can't immediately return fetched data.
What you can return is a promise. Good news, $http() returns one:
function getUsers() {
return $http({ method: 'GET', url: '/api/loginapi/userdetails' });
}
Then you can use your function:
getUsers().then(function(data) {
var details = data;
// Process your details!
});
You can access data there for sure, nothing is 'inside' $http, I suggest you pass in a callback to getUsers() and do whatever you want with the returned data:
var getUsers=function(callback){
$http({ method: 'GET', url: '/api/loginapi/userdetails' })
.success(function (data, status, headers, config) {
callback(data);
});
}
and use it like this inside your controller:
getUsers(function(users){
$scope.whatever = users;
})
I created plunkr for your question http://plnkr.co/edit/lqX4apmvnKM3i5jGZDQM?p=preview
$http return a promise. Please read details about promise at http://johnmunsch.com/2013/07/17/angularjs-services-and-promises/ . It is an important understanding if you want to write asynchronous application. This is another useful link - Inside my own Angular service, how do you get the return value back to the Controller that called the service? . Refer to answer. It explains how to use promise and deffered in angularjs.
var app = angular.module('plunker', []);
app.service('UserService', ['$http', '$q',
function($http, $q) {
this.getUser = function() {
return $http({
method: 'GET',
url: 'data.json'
});
};
}
]);
app.controller('MainCtrl', function($scope, UserService) {
$scope.user = {};
UserService.getUser().then(function(response){
$scope.user = response.data;
});
});

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

I have the following code in the controller.js,
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = dataService.getData();
});
But, I think I m probably making a mistake with CORS related issue. Can you please point me to the correct way to make this call? Thanks much!
First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.
I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.
For simplicity, here's your same code re-written with a function callback provided by the calling controller:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
Now, $http actually already returns a $promise, so this can be re-written:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.
I suggest you use Promise
myApp.service('dataService', function($http,$q) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
deferred = $q.defer();
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, we can resolve promise and we can access it in controller
deferred.resolve();
}).error(function(){
alert("error");
//let the function caller know the error
deferred.reject(error);
});
return deferred.promise;
}
});
so In your controller you can use the method
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.
No need to promise with $http, i use it just with two returns :
myApp.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data;
}).error(function(){
alert("error");
return null ;
});
}
});
In controller
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
Try this
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.
So you need to use what we call promise. Read how angular handles it here, https://docs.angularjs.org/api/ng/service/$q. Turns our $http support promises inherently so in your case we'll do something like this,
(function() {
"use strict";
var serviceCallJson = function($http) {
this.getCustomers = function() {
// http method anyways returns promise so you can catch it in calling function
return $http({
method : 'get',
url : '../viewersData/userPwdPair.json'
});
}
}
var validateIn = function (serviceCallJson, $q) {
this.called = function(username, password) {
var deferred = $q.defer();
serviceCallJson.getCustomers().then(
function( returnedData ) {
console.log(returnedData); // you should get output here this is a success handler
var i = 0;
angular.forEach(returnedData, function(value, key){
while (i < 10) {
if(value[i].username == username) {
if(value[i].password == password) {
alert("Logged In");
}
}
i = i + 1;
}
});
},
function() {
// this is error handler
}
);
return deferred.promise;
}
}
angular.module('assignment1App')
.service ('serviceCallJson', serviceCallJson)
angular.module('assignment1App')
.service ('validateIn', ['serviceCallJson', validateIn])
}())
Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.
The service:
MyApp.service('getData',
[
'$http',
function($http) {
this.getQuote = function(ticker) {
var _url = 'https://www.google.com/finance/info?q=' + ticker;
return $http.get(_url); //Simply return the promise to the caller
};
}
]
);
The controller:
MyApp.controller('StockREST',
[
'$scope',
'getData', //<-- the service above
function($scope, getData) {
var getQuote = function(symbol) {
getData.getQuote(symbol)
.success(function(response, status, headers, config) {
var _data = response.substring(4, response.length);
var _json = JSON.parse(_data);
$scope.stockQuoteData = _json[0];
// ticker: $scope.stockQuoteData.t
// last price: $scope.stockQuoteData.l
// last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
// last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
})
.error(function(response, status, headers, config) {
console.log('### Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
});
};
getQuote($scope.ticker.tick.name); //Initialize
$scope.getQuote = getQuote; //as defined above
}
]
);
The HTML:
<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>
At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.
When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.
myApp.service('serverOperations', function($http) {
this.get_data = function(user) {
return $http.post('http://localhost/serverOperations.php?action=get_data', user);
};
})
myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {
serverOperations.get_data(user)
.then( function(response) {
console.log(response.data);
}
);
})

AngularJS - $q's Promise not cascading to controller properly

While I'm reading up on Pluralsight's fundamentals on AngularJS, I'm stumped with my $http + $q.defer() not working as it should be. It seems like even the deferred variable has been resolved, the change still doesn't cascade onto the controller.
My View:
<li class="row" ng-repeat="item in jsonData.Items">
My Service:
mediaApp.factory('ServiceData', function ($http,$q) {
return{
getJson: function ($scope) {
var deferred = $q.defer();
$http(
{
method: 'GET',
url: url
}).
success(function (data, status, header, config) {
$timeout(function () {
deferred.resolve(data);
});
})
}
My Controller:
$scope.jsonData = ServiceData.getJson($scope);
Meanwhile, these lines of code work on the controller:
ServiceData.getJson($scope).
then(function (data) {
$scope.jsonData = data;
});
Can someone enlighten me on this? I believe the workaround is already proper, but I would like to understand why certain implementations of the code doesn't work as expected.
What gives?
You aren't returning the promise from getJson
mediaApp.factory('ServiceData', function ($http, $q) {
return {
getJson: function ($scope) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'json.json'
}).
success(function (data, status, header, config) {
deferred.resolve(data);
})
/* return the promise*/
return deferred.promise
}
}
})
Since $http returns a promise....you could to the same thing without creating your own deffered and just return the $http call
DEMO

Categories

Resources