2

I have services and controllers written in AngularJS, in which I am sending a post request to Node.js Application and using send status and code to send a error message like Username already exists orWrong email and password but I am not getting How to show these errors in frontend HTML. Like after submit is pressed probably. How would you go about it?

$http.post('/register', registerUser).then(function(response){
                console.log(response.data);
}

How will I show response .data in the HTML. I read about $error in angular but I don't think it will work in my case as mine is a custom error.

Thanks

3 Answers 3

14

Your HTML should be something like:

<div ng-if="errorMessage">{{ errorMessage }}</div>

Then you can modify $scope.errorMessage to display it:

$http.post('/register', registerUser).then(function(response){
    switch(response.data) {
        case 'loginExists':
            $scope.errorMessage = 'Username already exists';
            break;
        case 'loginError':
            $scope.errorMessage = 'Wrong email and password';
            break;
        default:
            $scope.errorMessage = false;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Looks logically correct. Let me try it. I'll get back to you.
4

You can use alert with Bootstrap:

<div ng-show="hasError">
<alert ng-repeat="error in errors track by $index" type="danger"  close="closeAlert($index)">{{error}}</alert>
</div>

in controller:

$scope.errors = [];
$scope.hasError = false;
$scope.closeAlert = function (index) {
    $scope.errors.splice(index, 1);
}

$http.post('/register', registerUser).then(function(response){
switch(response.data) {
    case 'error1':
        $scope.hasError = true;
        $scope.errors.push('error1');
        break;
    case 'error2':
        $scope.hasError = true;
        $scope.errors.push('error2');
        break;
    default:
        $scope.hasError = true;
        $scope.errors.push("I don't know whats going on");
    }
 }
};

You can use it everywhere.

Comments

0

I think that is better like this:

Message error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.