如何返回"然后()" angularjs中的方法?

时间:2016-11-22 09:00:25

标签: asp.net angularjs asp.net-mvc

我的情况:

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是一个像:

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

我想在提交访问结果后返回then()方法。我怎么能这样做?

更新

在控制器中:

[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);
}

4 个答案:

答案 0 :(得分:2)

首先,您应该避免将$用于自己的功能。

关于您的问题,您需要使用$q。你应该使用什么角度优惠给你。

让我告诉你:

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;
    }
});

现在,在您的控制器中,您可以使用

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

答案 1 :(得分:1)

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

        // validating...

        return success
    },
    submit: function (x) {
        var d = $q.defer();
        // 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
                        d.resolve('success');
                    } else {
                        let msg = data['ErrorMessage'];
                        d.reject(msg);
                        // return then() with errorCallback() function                            
                    }
                }
            }

            xhttp.open('POST', '/account/register');
            xhttp.send(formData);
        }
         else {
           d.reject('error');
        }
        return d.promise;
    }
}

return o
});

答案 2 :(得分:1)

伙计,我做了一个承诺的样本函数

$ q应该作为依赖注入

class AppUserService {


 constructor($http,CONFIG_CONSTANTS,$q, AuthService) {
   this.API_URL = CONFIG_CONSTANTS.API_URL;
   this.$http = $http;
   this.$q = $q;
   this.api_token = AuthService.api_token;
 }

 getAppUserList() {
  const deferred = this.$q.defer();
  this.$http.get(`${this.API_URL}/customer?api_token=${this.api_token}`)
      .success(response => deferred.resolve(response))
      .error(error =>  deferred.reject(error));
   return deferred.promise;
 } 
}

以ES6形式。

使用方法:

AppUserService.getAppuserList().then(success => {
  // code for success
},error => {
  // code for error
})

答案 3 :(得分:1)

    submit: function (x) {

            return $q(function (resolve, reject) {
                // 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']) {
                                resolve(data);
                                // return then() with successCallback() function
                            } else {
                                let msg = data['ErrorMessage'];
                                reject(msg);                           
                            }
                        }
                    }

                    xhttp.open('POST', '/account/register');
                    xhttp.send(formData);
                }
               else
                 reject('x not valid');   
              }
            }
        }

但我建议使用有角度的$http服务。