Tân Nguyễn Tân Nguyễn - 17 days ago 6
AngularJS Question

How to return "then()" method in angularjs?

My case:

app.js
:

let app = angular.module('myApp', []);

app.controller('login', function ($scope, $login) {
$scope.account = {};

$scope.loginForm_submit = function ($event, account) {
$event.preventDefault();

if ($login.isValid(account)) {
$login.submit(account);

// goal:

$login.submit(account).then(function () {
window.location = '/'
}, function (msg) {
console.log(msg)
});
}
};
});


login.js
:

app.factory('$login', function () {
let o = {
isValid: function (x) {
let success = false;

// validating...

return success
},
submit: function (x) {
// prevent to force submitting
if (this.isValid(x)) {
let formData = new FormData(), xhttp = new XMLHttpRequest();

// appending data to 'formData' via 'x'...

xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
let data = JSON.parse(xhttp.responseText);

if (data['Success']) {
// return then() with successCallback() function
} else {
let msg = data['ErrorMessage'];

// return then() with errorCallback() function
}
}
}

xhttp.open('POST', '/account/register');
xhttp.send(formData);
}
}
}

return o
});


data
is an object like:

let data = {
'Success': false,
'ErrorMessage': 'Invalid login attempt.'
};


I want to return
then()
method after submitting to access result. How can I do that?

UPDATE:

In controller:

[HttpPost]
public async Task<ObjectResult> Login(LoginViewModel model)
{
IDictionary<string, object> value = new Dictionary<string, object>();
value["Success"] = false;

if (ModelState.IsValid)
{
// login
value["Success"] = true;
}

return new ObjectResult(value);
}

Answer

First of all, you should avoid using $ for your own functions.

About your problem, you need to use $q. And you should use what angular offers to you.

Let me give you this :

app.factory('loginFactory', function($q, $http) {
    var ret = {
        isValid: isValid,
        submit: submit
    }

    return ret;

    function isValid(x) {
        // Your code ...
        return false;
    }

    function submit(x) {
        // x is your form data, assuming it's a JSON object

        var deferred = $q.defer();

        // Assuming you're posting something
        $http.post('yoururl', x,{yourConfigAsAnObject: ''})
        .then(function(success){
            console.log(success.data);
            deferred.resolve(success.data);
        }, function(error) {
            console.log(error);
            deferred.reject(error);
        });

        return deferred.promise;
    }
});

Now, in your controller, you can use

loginFactory.submit(yourParam).then(function(success){
    // Your code
}, function(error) {
    // Your code
});