I have a controller with the two functions.function "fileHistory" will be loaded first.
and i need to same call the same function from another function success callback.
i tried this way- but i am getting error
here is my Controller code
function cBookController($scope,$http) {
$scope.fileHistory = function() {
$http({
url: '/123/rest/getUploadDetails',
method: "GET"
})
.success(function (data, status) {
console.log(data);
$scope.fileHistory = data;
})
.error(function (data, status) {
alert("Error in get history details process");
});
}
$scope.fileHistory();
$scope.checkStatus = function(uploadedFileId) {
$http({
method: 'GET',
url: '/123/rest/checkStatus',
})
.success(function(data, status, headers, config) {
//here i need to get the new datafrom fileHistory service.
$scope.fileHistory();
})
}
}
By checking in your code I see that inside the $http success callback of fileHistory function, you override your function with response data from $http
Your fileHistory is a function at first. But after your promise is executed you are assigning this to a data variable and overriding it.
Change following line to something else -
//$scope.fileHistory = data; // change this line
$scope.fileHistoryData = data;
Related
Here I'm using Angularjs1.x and here is my condition. If condition is success then show the table otherwise throw an error. I know some code if its Success.
AngCtrl.Js
$scope.BtnCall = function () {
ServiceCntrl.CallData().then(function (d) {
$scope.EmpData = d.data;
});
}
AngService.Js
eApp.service("ServiceCntrl", function ($http) {
var xx = '';
xx= $http({
data: formData,
method: 'post',
url: Url,
datatype: "json"
}).success(function (rsp) {
RspData = rsp;
return RspData;
}).error(function (rsp) {
console.log('Error');
});
return xx;
};
Your x.then receives two functions x.then(function(){}, function(){}); first function is called when promise is successfully resolved and second function is called if promise is rejected(failed).
If your service function is return $http promise then your first function can have a parameter named(anything you like) and it will have response data that you can use. Second function can receive error parameters if any.
you should look at angular $http service documentation.
If your service is returning the promise of the get request, then you can write
$scope.BtnCall = function () {
var x = ServiceCntrl.CallData();
x.then(function(response) {
//Success callback
//code on success goes here
//response.data
}, function(response) {
//error callback
//code on error goes here
// server returns response with an error status.
});
you can use the ng-show/ng-hide to show and hide the contents on the html page.
You can write your success/fail code as the following:
$scope.BtnCall = function() {
var x = ServiceCntrl.CallData();
x.then(function(result) {
// Success code here
// Do something and resolved the promise
}, function(reason) {
// Error code here
// You may handle/reject the reason in params
});
});
See also the Angular docs for $q.
The AngularJS $http service makes a request to the server, and returns a response
The example above executes the $http service with an object as an argument. The object is specifying the HTTP method, the url, what to do on success, and what to do on failure.
$scope.BtnCall = function () {
ServiceCntrl.CallData().then(function (d) {
$scope.EmpData = d.data;
});
}
AngService.Js :
eApp.service("ServiceCntrl", function ($http) {
var xx = '';
xx= $http({
data: formData,
method: 'post',
url: Url,
datatype: "json"
}).success(function (rsp) {
RspData = rsp;
return RspData;
}).error(function (rsp) {
console.log('Error');
});
return xx;
};
I want to initialize a globle variable "$rootScope.SegmentSelectedGlobal" at the starting of application only.
This globle variable get data from a service.
If i execute service through controller, its working fine.
But when i execute it from App.run, no value is being assinged an d no error is being reported.
Here is the code:
App.run :
app.run(['$rootScope','DashboardService', function($rootScope,DashboardService) {
$rootScope.SegmentSelectedGlobal = DashboardService.getSegments();
}]);
Service :
app.service("DashboardService",function($q,$http,errorMessages){
var allSegements = [];
return {
// For selected Only
getSegments : getSegments
}
function getSegments(){
var deferred = $q.defer();
$http({
url: "/getAllSegments",
method: "GET"
}).success(function (data, status, headers, config) {
deferred.resolve(data);
allSegements = data;
}).error(function (data, status, headers, config) {
//logger.logError('Error while retrieving Versions details');
allSegements = null;
});
return allSegements;
}
});
Thanx for your help.
It returns undefined because at return allSegements allSegements is undefined.
Your using a promise, yet your forgot to return it properly
app.service("DashboardService",function($q,$http,errorMessages){
var allSegements = [];
return {
// For selected Only
getSegments : getSegments
}
function getSegments(){
var deferred = $q.defer();
$http({
url: "/getAllSegments",
method: "GET"
}).success(function (data, status, headers, config) {
deferred.resolve(data);
allSegements = data;
}).error(function (data, status, headers, config) {
//logger.logError('Error while retrieving Versions details');
deferred.reject();//--------- REJECT IF ERROR
});
return deferred.promise;//------- RETURN THE PROMISE
}
});
app.run(['$rootScope','DashboardService',function($rootScope,DashboardService) {
// use then to get the data from your promise ince it's ready
DashboardService.getSegments().then(function(data){
$rootScope.SegmentSelectedGlobal = data;
});
}]);
Note if you want to wait for the promised to be resolved before loading your page, use the resolve attribute (available in both ngRoute/ui-router) :
resolve:{
segments:['DashboardService', function(DashboardService){
return DashboardService.getSegments();//we return the promise, the resolve parameter will take the result, in case of error page won't be loaded.
}];
}
In my angularJS application, I have set data received from one controller's ajax and put in factory method to reuse in other controllers. The problem is when user reload page, this factory method is useless.
app.factory('factory', function () {
return {
set: set,
get: get
}
});
app.controller ('testController', function ($scope, factory) {
if (factory.get('name')) {
$scope.name= factory.get('name');
} else {
$http.get(url).then(function(res) {
$scope.name= res.name;
factory.set('name', res.name);
});
}
});
What is the best way to retrieve this check in factory method which will get value from factory, if not there take from http service and in controller common code needs handle these two cases that done factory method?
Here when data taken from http service it returns promise otherwise plain value.
This code will fetch data from server if the 'cachedResult' variable is not set, otherwise return a promise from the stored variable.
app.factory('factoryName', ['$http','$q', function($http,$q) {
var cahedResult = null;
var myMethod = function(args) {
var deferred = $q.defer();
if (cahedResult){
deferred.resolve({ data : cahedResult });
return deferred.promise;
}
$http.get(....).then(function(response){
cahedResult = response.data;
deferred.resolve({ data : cahedResult });
},function(error){
deferred.reject('error');
});
}
};
return {
myMethod : myMethod
}
])
But you could also store the data in local storage or in a cookie when the first controller fetch the info so that it's available even if user refresh the browser.
First create a factory :
app.factory('factoryName', ['$http','$q', function($http,$q) {
return {
getData : function(arg1,arg2) {
return $http.get('/api-url'+arg1+'/'+arg2)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
return $q.reject(response.data);
});
}
}
}])
Provide every api details in this factory, so you can use this factory in multiple controllers.
In Controller inject the factory (factoryName) as a dependency.
app.controller ('testController',['$scope', 'factoryName', function($scope, factoryName) {
factoryName.getData(arg1,arg2,...)
.then(function(data) {
console.log(data);
}, function(error){
console.log(error);
});
}]);
For detailed description :- http://sauceio.com/index.php/2014/07/angularjs-data-models-http-vs-resource-vs-restangular/
Directly return a promise from your factory
app.factory('factoryName', function () {
var connectionurl ='...'; //Sample: http://localhost:59526/Services.svc
return {
connectionurl : connectionurl ,
methodName: function (parameters) {
$http({
method: 'GET',
url: connectionurl + 'servicemethod_name'
})}
}
}
});
In this case your controller will look like
app.controller ('testController', function ($scope, factoryName) {
factoryName.methodName(parameters).then(function(){
$scope.variable=response.data;
/*binding your result to scope object*/
}, function() {
/*what happens when error occurs**/
});
});
Other way is directly bind to a scope object through success callback function
app.factory('factoryName', function () {
var connectionurl ='...'; //Sample: http://localhost:59526/Services.svc
return {
connectionurl : connectionurl ,
methodName: function (parameters,successcallback) {
$http({
method: 'GET',
url: connectionurl + 'servicemethod_name'
}).success(function (data, status, headers, config) {
successcallback(data);
})
.error(function (data, status, headers, config) {
$log.warn(data, status, headers, config);
});
}
}
});
In this case your controller will look like
app.controller ('testController', function ($scope, factoryName) {
factoryName.methodName(parameters,function(response){
/* your success actions*/
$scope.variable=response;
});
});
In the second case your error is handled in the factory itself. How ever you can also use errorcallback function.
I am new to AngularJS and wanted to try out the $resource functionality.
I have this code:
.factory('GetTasksService', function($resource, BASE_URL) {
return $resource(BASE_URL + 'api/tasks');
})
.controller('TasksCtrl', function ($scope, $http, BASE_URL, GetTasksService) {
$scope.tasks = GetTasksService.query();
$scope.getTasks = function () {
$http({ url: BASE_URL + 'api/tasks', method: 'GET' })
.success(function (data, status, headers, config) {
$scope.tasks = data;
})
.error(function (data, status, headers, config) {
alert("call did not work");
});
}
});
The getTasks function works as expected - returning an array of:["taska", "taskb"] as it should.
The GetTasksService.query() however returns an array of [{"0":"t","1":"a","2":"s","3":"k","4":"a"}, {"0":"t","1":"a","2":"s","3":"k","4":"b"}]
Can anyone tell me what I am doing wrong?
There is an option when specifying an action for an ngResource called isArray;
The default action query sets this as true by default, so you need to set set the action like:
query : {
method : 'GET',
isArray : false
}
I am getting the following error reported on angular.min.js
0x800a1391 - JavaScript runtime error: 'Error' is undefined
with the following code:
Javascipt:
function Sucess()
{
//close
}
function Save()
{
var e = document.getElementById('FormDiv');
scope = angular.element(e).scope();
scope.Apply(Sucess)
}
My Angular scope function:
function RolesCtrl($scope, $http, $location)
{
$scope.Apply = function (CallBackSucess) {
var userId = getQSP('uid', decode(document.URL));
$http({
method: 'POST', url: 'MultiRole.aspx/Apply',
data: {}
}).
success(function (data, status, headers, config) {
// this callback will be called asynchronously
CallBackSucess();
$scope.f = data.d;
}).
error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.name = 'error';
})
}
}
Everything seems to be working fine until CallBackSucess() call is made which throws the error:
0x800a1391 - JavaScript runtime error: 'Error' is undefined
The CallBackSucess argument is passed to the .Apply() method. It is not passed to the .success() method - they are chained methods with separate scopes. Thus, in the .success() callback function, CallbackSucess() is not defined when you try to call it and thus you get an error.
Also, do you really mean to spell Sucess incorrectly?
FYI, I had to format your code like this in order to see what was actually going on:
function RolesCtrl($scope, $http, $location) {
$scope.Apply = function (CallBackSucess) {
var userId = getQSP('uid', decode(document.URL));
$http({
method: 'POST',
url: 'MultiRole.aspx/Apply',
data: {}
}).success(function (data, status, headers, config) {
// this callback will be called asynchronously
CallBackSucess();
$scope.f = data.d;
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.name = 'error';
})
}
}