HI all i have 2 question
angular try to handle server $http error globally. so written below code in app.js
angular.module('mname',[])
.config(function ($provide, $httpProvider) {
$provide.factory('ErrorInterceptor', function ($q) {
return {
responseError: function(rejection) {
//console.log(JSON.stringify(rejection));
alert('Error:==>'+rejection.status+"===>"+rejection.statusText);
return $q.reject(rejection);
}
};
});
1) Here I can able to get that alert if 404 error.
But if server through any code error like missing variable or etc... but connection state is 200 .. that time how can i manage??
can't come inside this responseError: area .
2) I wrote one method for dialog factory to display the errors and message as Factory. I can able to include inside the controller to get working. How can use inside "responseError:" area . (refer above code)
Related
I'm made android project with ionic V1. I want make app send some function before app close with Cordova event. I try use pause to send data to server but I have stuck in sending data in app.run(). This my code in app.js
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
document.addEventListener("pause", onPause, false);
});
function onPause($http) {
$http.get('https://localhost:88/web.php?tN=off&f12=123456789')
.then(function(response){
console.log(response);
}, function(error){
//there was an error fetching from the server
});
}
});
And this error from debugger
Uncaught TypeError: Cannot read property 'get' of undefined
I don't know where what wrong with this code. I used in controller.js it work correctly but in app.js it doesn't work. Please help me to solved this problem. Thanks
$http is missing is your run() parameters
My question is about $resource's interceptor(responseError). I want to emphasize that the angularjs I based on is V1.3.6.
Problem:
app.factory('authInterceptor',['$q', '$location', '$log', function($q, $location, $log){
$log.debug('this is a regular factory with injection');
return {
responseError: function(response){
console.log(response)
// problem is that I cant check 401 by response.status,
// because the response here is AN ERROR OBJECT like `SyntaxError: ...`. Anyway to get the status?
return $q.reject(response);
}
}
}])
When I get 401 response, responseError's arguments is AN ERROR OBJECT like SyntaxError: Unexpected token U because the reponse from server is plain text Unathorized with status 401.
But I want to get the response.status, and do something if it is 401.
Any help will be appreciated.
This question should be closed because I finally found answer myself.
When response is 401/404 and anything besides 200, transformResponse still executed and an error occurred! This error just cover the normal response(has status property), so I never get the original response inside interceptor!
I think it's stupid to execute transformResponse if the response's status is not 200! And inside transformResponse, you can't access status code...
Here is a simple interceptor that handles 401s, as well does some configuration:
angular.module('notesApp', [])
.factory('AuthInterceptor',['AuthInfoService', '$q', function(AuthInfoService, $q) {
return {
responseError: function(responseError) {
if (responseError.status === 401) { // authentication issue
//redirect user to login or do something else...
}
return $q.reject(responseError);
}
};
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
}]);
** Here is an interceptor that only intercepts incoming responses with a non-200 status code.**
If the status code is 401, the user is redirected to the login page. In this case, the promise is rejected so that the controller or service still sees a failure
I'm trying to use angular ngResource module to fetch data from json file but I get an error 404 on the console - the URL is being concatenated with code following the call to get function.
Here is the error:
localhost prefix/test_data/data.json/function%20(data)%20%7B%20%20%20%20%20%20%20%20%20%20%20%20console.log(data);%20%20%20%20%20%20%20%20%7D
here is the code I'm using:
the json service -
angular.module('jsonServices',['ngResource']).factory('JsonService',
function ($resource) {
return $resource('/test_data/data.json');
});
the controller using the service:
angular.module('myApp.controllers')
.controller('mainController', function ($scope, JsonService) {
JsonService.get(function (data) {
console.log(data);
});
});
the app js that starts it all:
angular.module('myApp',['myApp.controllers','jsonServices','ui.router'])
.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('home',{
url:'/home',
template:'some template path goes here',
controller:'mainController'
};
});
As you can see the "function(data)" is being added to the url as a string. one more thing is when I try to access the json file browsing to its location I can see the content of the json file OK.
Does anyone got this problem before and find a way to solve it? Is there something I'm doing wrong or missing here?
Thanks,
Eran
Found the problem, it seems that I used a bower package call ng-resource instead of angular-resource.
On my AngularJS sample project, I know that I have a service method which SHOULD throw a JavaScript error.
Using Firebug, I confirm that a JS error is thrown when resolving a promise from a $resource (TypeError: phone.images is undefined); but, the error never appears in the Firebug console.
How can I get the resource to 'fail fast' and propagate the error up the call stack?
Here is the service code:
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
Here is the controller (which fails silently):
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
function($scope, $routeParams, Phone) {
$scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
//JS error SHOULD be thrown here:
$scope.mainImageUrl = phone.images[0];
});
...
}]);
I don't want the code to fail silently! How can I fix it?
Ideally, I would like to fix it throughout the framework, rather than putting in special error handling code for each service or resource call.
You need to add the error callback to your get call:
Phone.get({phoneId: $routeParams.phoneId}, function(phone){
// Do Stuff with phone object
}, function(error) {
alert("Y U NO RETURN PHONE?");
// Handle error accordingly
});
Here is the documentation for $resource
If you'd like to generically handle errors for AJAX requests through the angular framework, then you'd probably like something like an http interceptor (Check the interceptors section). This kind of paradigm requires that all requests pass through your interceptor service to be handled in a generic fashion.
I'm trying to re-direct my users if they pass my form validation (checking usernames and passwords against database values).
The validation works fine but in my .Success function the redirect doesn't seem to be working, it produces the error: 'ReferenceError: $window is not defined'.
Here's the code:
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorUserName = data.errors.userName;
$scope.errorUserPassword = data.errors.userPassword;
} else {
// if successful, bind success message to message
$scope.message = data.message;
$window.location=('twitter.com');
}
});
I've tried changing the location path but nothing seems to be working. Any ideas?
Thanks!
LazyTotoro
$window needs to be injected.
To inject it you simply add it as a parameter to your controller function and Angular will automatically take care of the rest.
For example:
app.controller('MyController', function MyController($scope, $window) {
$window.location = 'http://stackoverflow.com'
});
You can read more about dependency injection in AngularJS here.
If you don't need a full page reload you should instead inject and use $location:
// get the current path
$location.path();
// change the path
$location.path('/newValue');