This is my controller:
angular.module("AuthenticationApp", ["BaseApp"])
.controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
var self = this;
self.add = function() {
BaseService.add.user(self.user)
.catch(function(errorResponse) {
self.cerrorMessages = errorResponse.data;
});
};
This is my BaseApp
/ factory:
angular.module("BaseApp", [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}])
.factory("BaseService", ["$http", "$window", function($http, $window) {
var self = this;
self.add = {
user: function(user) {
$http.post("/users/", user)
.then(function(response) {
$http.post("/api-auth/login", user)
.then(function(response) {
$window.location.href = "/";
});
// if there are errors, rewrite the error messages
}).catch(function(response) {
for (prop in response.data) {
if (prop == "email") {
response.data[prop] = "Please enter a valid email address.";
} else if (prop == "username") {
response.data[prop] = "Please enter a valid username";
}
}
});
}
};
When I try to run this code and call self.add()
on my controller, I get an error saying TypeError: Cannot read property 'catch' of undefined
pointing to the line .catch(function(errorResponse) {
in my controller. I'm guessing this is because there is no then()
function.
What should I do to properly override the errResponse
parameter which is passed to the controller's .catch()
function (without having a .then()
function because nothing is needed to be done if it is successful)?