I'm quite new to angularjs and I'm trying to figure out how to use a good and proper error handling when calling web api.
I have two methods which depends on each other, so I need to wait for the first method to finish before calling the second method. But if the web api returns internal server error (of something else), how should I take care of if in a proper way?
My firstMethod causes an error right now, but the $scope.scopeMethod is still keep on going. Should I use the error handling there instead?
angular.module("Module")
.controller("MyController",
function ($scope, $log, SecurityService) {
$scope.scopeMethod= function() {
SecurityService.firstMethod()
.then(function(firstResult) {
$scope.firstResult= firstResult;
SecurityService.secondMethod(firstResult)
.then(function (secondResult) {
$scope.secondResult= secondResult;
//Do stuff with secondresult
});
});
});
}
}
)
SecurityService:
angular.module('Security', []);
angular.module("Security")
.factory("SecurityService",
function($http, $cookies, $rootScope, $log) {
var service = {};
//firstMethod
service.firstMethod = function () {
return $http.get('/api/security/')
.then(function(result) {
return (result.data);
}, function(error) {
$log.error(error);
});
}
//secondMethod
service.secondMethod = function(username) {
return $http.get('/api/security/' + username)
.then(function(result) {
return (result.data);
});
}
return service;
}
);
Related
I've been struggling with this for a few days now and can't seem to find a solution.
I have a simple listing in my view, fetched from MongoDB and I want it to refresh whenever I call the delete or update function.
Although it seems simple that I should be able to call a previously declared function within the same scope, it just doesn't work.
I tried setting the getDispositivos on a third service, but then the Injection gets all messed up. Declaring the function simply as var function () {...} but it doesn't work as well.
Any help is appreciated.
Here's my code:
var myApp = angular.module('appDispositivos', []);
/* My service */
myApp.service('dispositivosService',
['$http',
function($http) {
//...
this.getDispositivos = function(response) {
$http.get('http://localhost:3000/dispositivos').then(response);
}
//...
}
]
);
myApp.controller('dispositivoController',
['$scope', 'dispositivosService',
function($scope, dispositivosService) {
//This fetches data from Mongo...
$scope.getDispositivos = function () {
dispositivosService.getDispositivos(function(response) {
$scope.dispositivos = response.data;
});
};
//... and on page load it fills in the list
$scope.getDispositivos();
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo);
$scope.getDispositivos(); //it should reload the view here...
$scope.dispositivo = '';
};
$scope.removeDispositivo = function (id) {
dispositivosService.removerDispositivo(id);
$scope.getDispositivos(); //... here
};
$scope.editDispositivo = function (id) {
dispositivosService.editDispositivo(id);
$scope.getDispositivos(); //... and here.
};
}
]
);
On service
this.getDispositivos = function(response) {
return $http.get('http://localhost:3000/dispositivos');
}
on controller
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo).then(function(){
$scope.getDispositivos(); //it should reload the view here...
$scope.dispositivo = '';
});
};
None of the solutions worked. Later on I found that the GET request does execute, asynchronously however. This means that it loads the data into $scope before the POST request has finished, thus not including the just-included new data.
The solution is to synchronize the tasks (somewhat like in multithread programming), using the $q module, and to work with deferred objects and promises. So, on my service
.factory('dispositivosService',
['$http', '$q',
function($http, $q) {
return {
getDispositivos: function (id) {
getDef = $q.defer();
$http.get('http://myUrlAddress'+id)
.success(function(response){
getDef.resolve(response);
})
.error(function () {
getDef.reject('Failed GET request');
});
return getDef.promise;
}
}
}
}
])
On my controller:
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo)
.then(function(){
dispositivosService.getDispositivos()
.then(function(dispositivos){
$scope.dispositivos = dispositivos;
$scope.dispositivo = '';
})
});
};
Being my 'response' object a $q.defer type object, then I can tell Angular that the response is asynchronous, and .then(---).then(---); logic completes the tasks, as the asynchronous requests finish.
UPDATE
I am currently doing this, and I'm not sure why it works, but I don't think this is the correct approach. I might be abusing digest cycles, whatever those are.
First, I want to have the array navigationList be inside a service so I can pass it anywhere. That service will also update that array.
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigationList = [];
var getNavigation = function() {
ExtService.getUrl('navigation.json').then(function(data) {
angular.copy(data.navigationList, navigationList);
});
}
return{
getNavigation: getNavigation,
navigationList: navigationList,
}
}]);
Then in my controller, I call the service to update the array, then I point the scope variable to it.
ChapterService.getNavigation();
$scope.navigationList = ChapterService.navigationList;
console.log($scope.navigationList);
But this is where it gets weird. console.log returns an empty array [], BUT I have an ng-repeat in my html that uses $scope.navigationList, and it's correctly displaying the items in that array... I think this has something to do with digest cycles, but I'm not sure. Could anyone explain it to me and tell me if I'm approaching this the wrong way?
I have a main factory that runs functions and calculations. I am trying to run
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData : function () {
ExtService.getUrl('navigation.json').then(function(data) {
return data;
});
}
}
return: {
navigation: navigation
}
I did a console.log on the data before it gets returned and it's the correct data, but for some reason, I can't return it..
The ExtService that has the getUrl method is just the one that's typically used (it returns a promise)
In my controller, I want to do something like
$scope.navigation = ChapterService.navigation.getNavigationData();
in order to load the data from the file when the app initializes,
but that doesn't work and when I run
console.log(ChapterService.navigation.getNavigationData());
I get null, but I don't know why. Should I use app.run() for something like this? I need this data to be loaded before anything else is done and I don't think I'm using the best approach...
EDIT
I'm not sure if I should do something similar to what's being done in this jsfiddle, the pattern is unfamiliar to me, so I'm not sure how to re purpose it for my needs
My code for ExtService is
app.factory('ExtService', function($http, $q, $compile) {
return {
getUrl: function(url) {
var newurl = url + "?nocache=" + (new Date()).getTime();
var deferred = $q.defer();
$http.get(newurl, {cache: false})
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
}
});
EDIT 2
I'd like to separate the request logic away from the controller, but at the same time, have it done when the app starts. I'd like the service function to just return the data, so I don't have to do further .then or .success on it...
You are using promises incorrectly. Think about what this means:
var navigation = {
getNavigationData : function () {
ExtService.getUrl('navigation.json').then(function(data) {
return data;
});
}
}
getNavigationData is a function that doesn't return anything. When you're in the "then" clause, you're in a different function so return data only returns from the inner function. In fact, .then(function(data) { return data; }) is a no-op.
The important thing to understand about promises is that once you're in the promise paradigm, it's difficult to get out of it - your best bet is to stay inside it.
So first, return a promise from your function:
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData: function () {
return ExtService.getUrl('navigation.json');
}
}
return {
navigation: navigation
}
}])
Then use that promise in your controller:
app.controller('MyController', function($scope, ExtService) {
ExtService
.navigation
.getNavigationData()
.then(function(data) {
$scope.navigation = data;
});
})
Update
If you really want to avoid the promise paradigm, try the following, although I recommend thoroughly understanding the implications of this approach before doing so. The object you return from the service isn't immediately populated but once the call returns, Angular will complete a digest cycle and any scope bindings will be refreshed.
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData: function () {
// create an object to return from the function
var returnData = { };
// set the properties of the object when the call has returned
ExtService.getUrl('navigation.json')
.then(function(x) { returnData.nav = x });
// return the object - NB at this point in the function,
// the .nav property has not been set
return returnData;
}
}
return {
navigation: navigation
}
}])
app.controller('MyController', function($scope, ExtService) {
// assign $scope.navigation to the object returned
// from the function - NB at this point the .nav property
// has not been set, your bindings will need to refer to
// $scope.navigation.nav
$scope.navigation = ExtService
.navigation
.getNavigationData();
})
You are using a promise, so return that promise and use the resolve (.then) in the controller:
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData: function () {
return ExtService.getUrl('navigation.json'); // returns a promise
});
}
return: {
navigation: navigation
}
}
controller:
ChapterService
.navigation
.getNavigationData()
.then(function (data) {
// success
$scope.navigation = data;
}, function (response) {
// fail
});
This is a different approach, I don't know what your data looks like so I am not able to test it for you.
Controller
.controller('homeCtrl', function($scope, $routeParams, ChapterService) {
ChapterService.getNavigationData();
})
Factory
.factory('ChapterService', [ 'ExtService', function(ExtService) {
function makeRequest(response) {
return ExtService.getUrl('navigation.json')
}
function parseResponse(response) {
retries = 0;
if (!response) {
return false;
}
return response.data;
}
var navigation = {
getNavigationData: function () {
return makeRequest()
.then(parseResponse)
.catch(function(err){
console.log(err);
});
}
}
return navigation;
}])
I got an issue with Angular JS popup. I am submitting the data from the popup and I want to pass the data to a taskService so that it can call a WebAPI and store on to my DB.
This is my Call from BoardCtrl to open the Modal window
$scope.showAddTask = function () {
modalService.showModal({
templateUrl: "Partials/AddTask.html",
controller: "taskCtrl",
inputs: {
title: "Add Task"
}
}).then(function (modal) {
//debugger;
modal.element.modal();
modal.close.then(function (result) {
});
});
};
Now the user keys in the Task details and Submits. The call is in my taskCtrl
The debugger does hit the code below and I can see the values submitted by the end user. The problem I am facing is that I am getting an error
at taskService.addTask invocation
The error is "Cannot read property 'addTask' of undefined"
fpdApp.kanbanBoardApp.controller('taskCtrl', function ($scope, taskService) {
$scope.close = function () {
debugger;
taskService.addTask($scope.Name, $scope.Desc, $scope.Estimate, 1).then(function (response) {
$scope.result = response.data;
}, onError);
close({
name: $scope.name,
Desc: $scope.Desc,
Estimate: $scope.Estimate,
}, 500); // close, but give 500ms for bootstrap to animate
};
});
Here is my taskService
fpdApp.kanbanBoardApp.service('taskService', function ($http, $q, $rootScope) {
var addTask = function (name, desc, estimate, projectId) {
debugger;
//return $http.get("/api/TaskWebApi/AddTaskForProject").then(function (response) {
// return response.data;
//}, function (error) {
// return $q.reject(error.Message);
//});
};
});
Can some one please help/ guide me whats wrong here.
Note that I have got other method calls working fine in the same service and controller.
Thanks in Advance
Venkat.
You need to expose addTask method in service. Right now it's just a local variable which cannot be accessed from outside. When the service is constructed it should create proper object with necessary methods. So you should set addTask either with this.addTask = addTask or by returning object with such method:
fpdApp.kanbanBoardApp.service('taskService', function ($http, $q, $rootScope) {
var addTask = function (name, desc, estimate, projectId) {
return $http.get("/api/TaskWebApi/AddTaskForProject").then(function (response) {
return response.data;
}, function (error) {
return $q.reject(error.Message);
});
};
return {
addTask: addTask
};
});
Service always returns a singleton object and that can be used by application wide.
You forget to write method inside service context,
change var addTask to this.addTask
Code
fpdApp.kanbanBoardApp.service('taskService', function($http, $q, $rootScope) {
this.addTask = function(name, desc, estimate, projectId) {
return $http.get("/api/TaskWebApi/AddTaskForProject").then(function(response) {
return response.data;
}, function(error) {
return $q.reject(error.Message);
});
};
});
Hope this could help you. Thanks.
How can I use the fetched data in customersController in AnotherCustomersController
function customersController($scope, $http) {
$http.get("http://www.w3schools.com//website/Customers_JSON.php")
.success(function(response) {$scope.names = response;});
}
function AnotherCustomersController($scope){
//What should I do here??
}
Full Details Here
You can share data between controllers using $rootscope but I don't think this is a best practice so my solution contain usage of angular service -> plnkr
app.factory('CustomerService', function ($http) {
return {
fetchData: function () {
return $http.get('http://www.w3schools.com//website/Customers_JSON.php')
}
}
});
app.controller('customersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});
app.controller('AnotherCustomersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});
Additionally i have refactor your code so only one app is used on page. If you want to use more than one you have to bootstrap them manually -> Read More
I'm using Facebook connect to login my clients.
I want to know if the user is logged in or not.
For that i use a service that checks the user's status.
My Service:
angular.module('angularFacebbokApp')
.service('myService', function myService($q, Facebook) {
return {
getFacebookStatus: function() {
var deferral = $q.defer();
deferral.resolve(Facebook.getLoginStatus(function(response) {
console.log(response);
status: response.status;
}));
return deferral.promise;
}
}
});
I use a promise to get the results and then i use the $q.when() to do additional stuff.
angular.module('angularFacebbokApp')
.controller('MainCtrl', function ($scope, $q, myService) {
console.log(myService);
$q.when(myService.getFacebookStatus())
.then(function(results) {
$scope.test = results.status;
});
});
My problem is that i need to use the $q.when in every controller.
Is there a way to get around it? So i can just inject the status to the controller?
I understand i can use the resolve if i use routes, but i don't find it the best solution.
There is no need to use $q.defer() and $q.when() at all, since the Facebook.getLoginStatus() already return a promise.
Your service could be simpified like this:
.service('myService', function myService(Facebook) {
return {
getFacebookStatus: function() {
return Facebook.getLoginStatus();
}
}
});
And in your controller:
.controller('MainCtrl', function ($scope, myService) {
myService.getFacebookStatus().then(function(results) {
$scope.test = results.status;
});
});
Hope this helps.
As services in angularjs are singleton you can create new var status to cache facebook response. After that before you make new call to Facebook from your controller you can check if user is logged in or not checking myService.status
SERVICE
angular.module('angularFacebbokApp')
.service('myService', function myService($q, Facebook) {
var _status = {};
function _getFacebookStatus() {
var deferral = $q.defer();
deferral.resolve(Facebook.getLoginStatus(function(response) {
console.log(response);
_status = response.status;
}));
return deferral.promise;
}
return {
status: _status,
getFacebookStatus: _getFacebookStatus
}
});
CONTROLLER
angular.module('angularFacebbokApp')
.controller('MainCtrl', function ($scope, $q, myService) {
console.log(myService);
//not sure how do exactly check if user is logged
if (!myService.status.islogged )
{
$q.when(myService.getFacebookStatus())
.then(function(results) {
$scope.test = results.status;
});
}
//user is logged in
else
{
$scope.test = myService.status;
}
});