Assign variable from $http .success function to $scope.variable - angularjs

$scope.restaurants variable is emty. how to pass data to $scope.restaurants?
FoodSearchControllers.controller('homeCtrl', ['$scope', '$http', function($scope, $http) {
//restoranai
$http.post('http://appdev.milasevicius.com/server/index.php', {
"query": "SELECT * FROM n01_restaurant"
}).success(function(data, status) {
$scope.restaurants = data;
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
console.log($scope.restaurants);
}]);
Also, controller is called twice. Why is that?

Your console.log is called at a point where the $http call might not have returned yet. The post is an async call so if you move your console.log in your success function, you should see it. In short, $scope.restaurants is mostly likely being populated but you're trying to check it too early.

Related

MVC and Angularjs : promise does not waiting data

i'm newby in angularjs i researched on the internet but i couldn't find any suitable solution for my problem. I made an http call to get some data from controller. The controller side is okay. But the client-side, promise does not waiting data. Here codes that I wrote ;
//service code
angular.module("myApp").service('$myService', function ($http, $q) {
this.getDataArray = function () {
var deferred = $q.defer();
$http.get('../Home/GetDataArray')
.success(function success(response) {
deferred.resolve(response);
})
.error(function () {
console.log("error getting data array");
deferred.reject();
});
return deferred.promise;
};
}
// controller-code
angular.module("myApp").controller('dataController', function ($scope, $http, $myService) {
$scope.getDataFromService = function () {
$myService.getDataArray().then(function (response) {
$scope.dataArray = response.data;
});
};
});
}
When i call the getDataFromService method at first $scope.dataArray is empty, but the second call, $scope.dataArray is filled with data. Where is the problem? Thanks for helps.
Not an angular expert myself. This is just how I did it when I ran into the same problem. Try this:
Controller:
angular.module("myApp").controller('dataController',[ '$scope', 'Service1', '$http', function ($scope, Service1, $http) {
var deferred = Service1.getDataArray().$promise;
return deferred.then(function successCallback(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.dataArray = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}])
and service:
var service = angular.module("myApp").service('myService', ['ngResource']);
myService.factory('Service1', ['$resource',
function ($resource) {
return $resource('../Home/GetDataArray', {}, {
get: { method: 'GET', isArray: true },
});
}])
The idea is that your service isn't the one that should wait for a return, your controller is. So you should wait for the promise in your controller not your service. In my example I am using factories because, well, that's how I got around it in my project, you can try and implement this directly if you don't want to use a factory.

Angularjs rootscope value is undefined within the same controller in same function

I have set the username value in rootscope and when I try to use it within the same function it becomes undefined. I am not sure why this is happening.
controller
xxxApp.controller('listController', function($scope, $http, $location, $routeParams, $log, uiGridConstants, $rootScope) {
$scope.isSelected = false;
$scope.showSpinner = true;
$rootScope.loggedInUser = {};
$scope.user = {};
$http.get("/mdm/getLoggedInUsername")
.success(function(data, status, headers, config) {
$scope.user = data.user;
$rootScope.loggedInUser = $scope.user;
console.log("the logged in user is 1" +$scope.user);
console.log("the rootscope logged in user is 1" +$rootScope.loggedInUser);
})
.error(function(data, status, headers, config, statusText) {
console.log("Error ....the logged in user is 1" +$scope.user);
});
console.log("the rootscope logged in user is 2" +$scope.user);
$http.get("/mdmservice/services/entities/" +$rootScope.loggedInUser) // here rootscope is undefined and throws me 404 error not found
.success(
function(data, status, headers, config) {
$scope.entities = data;
})
.error(function(data, status, headers, config, statusText) {
$scope.error = true;
$scope.errorMessage = "A system error occured."
})
.finally(function () {
$scope.showSpinner = false;
});
That happens because $http calls are asynchronous - that means your program executes in the following order:
start first http call
print console log statement
start second http call
execute the success or error callbacks once the respective http call is finished
So to make your script work you can put the console.log statement and your second http call within the success callback of the first http call.
If you have trouble understanding this, I would recommend reading up on asynchronous programming in javascript with Callbacks and Promises.
That's because the first get function hasn't finished yet. You should call the second in callback of the first (in success area).

Ionic Framework: called service

I using this to save data to the service and called it again in the same controller after save it. But it didn't have value for the service. When i call the service again in another controller, it gave me the result i want.
.controller('HomeCtrl', function ($scope) {
$http.get(URL).success(function(data){
Service.thisData(data);
Service.getData(); // value = 1000
});
// call save data from service
// i didn't get any data from the service
Service.getData(); // value = undefined
};
So how do i get the data from service except inside the http.get??
Thanks.
I suggest you to write the api calls in a factory, and call that service in the controller, in which you need the data. You can call the same service in multiple controllers also.
As per my understanding, i hope this is your requirement. If not, please let me know, i will try my best.
You can refer to the plunkr code
http://plnkr.co/edit/G9MkVMSQ4VjMw8g2svkT?p=preview
angular.module('mainModule', [])
.factory('apiCallService', ['$http', '$q', '$log',
function ($http, $q, $log) {
var instance = {};
var config = null;
instance.apiCallToServer = function (config) {
var deferred = $q.defer();
$http(config)
.success(function (data, status, header, config) {
deferred.resolve(data);
})
.error(function (data, status, header, config) {
deferred.reject(status);
});
return deferred.promise;
};
return instance;
}])
.controller('FirstCtrl', ["$scope", "$log", "$location", "apiCallService",
function ($scope, $log, $location, apiCallService) {
var config = {
method: "get",
url: "/path"
};
$scope.successCallback = function (data) {
$log.log("success.");
$scope.data = data;
//data will be stored in '$scope.data'.
};
$scope.failureCallback = function (status) {
$log.log("Error");
};
apiCallService
.apiCallToServer(config)
.then($scope.successCallback, $scope.failureCallback);
}]);

Accessing returned scope method variables in another method in AngularJS

I have an Angular app with a service and a controller:
service.js
.factory('MyService', function ($http, $q) {
var api_url = 'http://localhost/api/';
var MyService = {
list: function (items_url) {
var defer = $q.defer();
$http({method: 'GET',
url: api_url + items_url}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
defer.reject(status);
});
return defer.promise;
},
...
}
});
controller.js
.controller("ItemsCtrl", function ($scope, MyService) {
$scope.getItems = function () {
MyService.list('items/').then(function(data) {
$scope.items = data;
});
};
$scope.addItems = function () {
$scope.getItems();
// why is this undefined ??!!!
console.log($scope.items);
};
The issue is that I want to call the $scope.getItems method inside the $scope.addItems method. Do I perhaps need to use $scope.apply(), as the returned value is a promise?
I think what I am displaying here is a general lack of understanding.
Change your controller like this:
.controller("ItemsCtrl", function ($scope, MyService) {
$scope.getItems = function () {
return MyService.list('items/').then(function(data) {
$scope.items = data;
});
};
$scope.addItems = function () {
$scope.getItems().then(function() {
// should be what you want this time
console.log($scope.items);
});
};
Your problem is when you call $scope.getItems(), http response is not returned yet, so $scope.items is not populated. You have to wait for all the promises are resolve to access items.
$scope.items is undefined because $http is an asynchronous communication. That is, when you call $scope.addItems(), it creates and sends the request to retrieve your list of items, then immediately moves on to the next line of code, which is to log $scope.items to the console. Since there's nothing in $scope.items yet, you get an undefined value.
If you want to operate on the data returned by the http call, you must guarantee that the data will be populated. In other words, any operations you want to perform on $scope.items should be called within your .then() block.
$scope.$apply() is used when you are not executing within an AngularJS context, to force the AngularJS framework to evaluate the expression. It will not help you here - you'll get an "$digest already in progress" error, or something along those lines.
Try this:
.controller("ItemsCtrl", function ($scope, MyService) {
$scope.getItems = function () {
MyService.list('items/').then(function(data) {
$scope.items = data;
console.log($scope.items);
});
};
$scope.addItems = function () {
$scope.getItems();
};
});
That is because $scope.getItems is asynchronous. Your callback (that added via then) is called after $scope.addItems executed.

Data from the factory when referenced to a scope does not show the value. AngularJS

I'm quite new on AngularJS and got stumped on a problem. I'm trying to get a value from a factory and was able to get the data, I attached a console.log() to the function to check, but when I tried to attached these data on a scope and do a check using console.log again, I’m getting a undefined message on the log.
I tried creating an object scope $scope.formWO= {}; and references it there but still I’m getting the same message. I don’t know if there are conflicts between scopes or an issue of displaying the page early before the system read or perform the function. I already read a lot on scopes but for somehow this problem seem to put my development into a complete stop. I don’t know which is which and would like definitely to get enlightened on this.
Here is the trimmed down controller just to give you an idea.
myApp.controller('ordersCtrl',
function ordersCtrl($scope, ngTableParams, dealerData, costElementData, totNoData, $http, $ekathuwa, $rootScope, $location, userService, $filter){
$scope.formWO = {};
$scope.addWorkOrder = function(){
$scope.modalHeader = "ADD NEW WORK ORDER";
$scope.modalType = "Add";
$ekathuwa.modal({
id: "modalWO",
scope: $scope,
templateURL: "./tpl/modal-wo.html"
});
$scope.$watch('formWO.dealer', function(newDealer, oldDealer){
if ( newDealer === oldDealer) {
return;
}
$http.get('api/profile/'+$scope.formWO.dealer).
success(function(data, status, headers, config){
$scope.formWO.outletno = data.outletno;
});
if ($scope.dealer === newDealer) {
return;
}
});
}
$scope.submitAddWorkOrder = function(cost_element, desc, ets, etc, cost_estimate, dealer){
totNoData.getTotNo(function(noData){
$scope.formWO.totno = noData;
});
console.log($scope.formWO.totno);
$scope.tableParams.reload();
}
});
Here is the factory:
myApp.factory('totNoData', function($http, $log){
return {
getTotNo: function(successcb){
$http({method: 'GET', url: 'api/totno'}).
success(function(data, status, headers, config){
successcb(data);
}).
error(function(data, status, headers, config){
$log.warn(data, status, headers, config);
});
}
}
});
What you probably want to do is move the log and, I guess, the reload, inside of the anonymous callback function that you're passing to 'getToNo'. Like:
$scope.submitAddWorkOrder = function(cost_element, desc, ets, etc, cost_estimate, dealer){
totNoData.getTotNo(function(noData){
$scope.formWO.totno = noData;
console.log($scope.formWO.totno);
$scope.tableParams.reload();
});
}
As it is, the log and the reload are happening before the callback is invoked. The order would go something like this:
call the getTotNo method
send the http request
step back out to submitAddWorkOrder
log $scope.formWO.totno (undefined)
call $scope.tableParams.reload();
... event loop / digest
http response received, success method called
callback invoked
$scope.formWO.totno is set
Async for the win!
EDIT:
A better to pattern is to return the promise that is returned from the $http call.
So change the service to:
getTotNo: function(){
return $http({method: 'GET', url: 'api/totno'});
}
And refactor your controller function to:
$scope.submitAddWorkOrder = function(cost_element, desc, ets, etc, cost_estimate, dealer){
totNoData.getTotNo().success(function (data) {
$scope.formWO.totno = noData;
console.log($scope.formWO.totno);
$scope.tableParams.reload();
}).error(function (data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}

Resources